Correct sscanf() prototype, "int sscanf ( const char * s,const char * format, ...);" or int sscanf (char * s,const char * format, ...);? [closed]

StackOverflow https://stackoverflow.com/questions/16625181

  •  29-05-2022
  •  | 
  •  

Question

Here is the prototype for the sscanf() function as described in the cplusplusreference(link) :

 int sscanf ( const char * s, const char * format, ...);

But I find something fishy about it.Not only does the type of first argument differ from many other string library functions like strcpy()(1) and strcat()(2) (const char* vs char*),but it also seems odd how can we make the array pointed by the first argument constant when the very purpose of the function is to write to it(alter the contents of the array) using that pointer!!

I mean, in int sscanf (const char * s,const char * format, ...); aren't we telling through the const qualifier that we can't change the array pointed by s using s? Is that a typo on that site, or do I fail to understand something?Please explain.

Was it helpful?

Solution

const char * s

sscanf does not write anything to the s string, s is an input string.

OTHER TIPS

In strcpy and strcat, the first argument (the destination) isn't const, because, of course, the function will modify them.

Generally, in function which modify a string, the first argument is the destination.

So, the correct prototype of sscanf is "int sscanf ( const char * s, const char * format, ...);", because it won't modify the source string, just read it.

If you aren't sure of the prototype of a function, the man page about this function is the reference

the purpose of making the first argument as constant for the function is to ensure that the function dosent in any manner or way change the contents of the string s during invokation .... it's to provide something like a read only access to the string s .....

the syntax seems fine.

still in doubt check in man.... or any C book .

By C99, the scanf prototype is:

int scanf(const char* restrict s, const char* restrict format, ...);

In this prototype:

int sscanf ( const char * s, const char * format, ...);
  • The int is a read-only output, the field match count or error report.
  • The const char *s is a read-only source from which characters are read.
  • The const char *format is a read-only specification of what the writable targets are.
  • The ... will become the list of writable addresses the output from the conversion go into, as detailed by format.

So, accordingly, the input string of s can certainly be a read-only string, since it's fairly important that sscanf be trusted not to overwrite the thing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top