Superfox il Volpone said:
Sorry people, what I posted it's part of a more large program and the
printf with I verified it was wrong
For context, here's the code you posted:
char* stringa = "18/2005"
char mese[3]; char anno[5];
int i_letture;
i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);
mese[2] = anno[4] = '\0';
Please read <
http://cfaj.freeshell.org/google/>.
This also demonstrates why you should always post a small, complete,
compilable program. We can't guess whether the part you didn't post
is what's causing the problem (in this case, it was). What you posted
wasn't even a correct code fragment; the declaration of stringa is
missing a semicolon, an error that the compiler would have caught.
Don't try to re-type your code; copy-and-paste *exactly* what you fed
to the compiler.
I solved but I don't understand one thing :
the sscanf works with '&mese' and 'mese' in the correct manner : maybe
it's the compiler (GCC) that does some correction ?
Given, for example,
char anno[5];
the expression "anno", an array name, is implicitly converted (in most
contexts) to a pointer to the array's first element; in this case, the
resulting expression is of type char*. The expression "&anno" yields
the address of the array; the resulting expression is of type
char (*p)[5], i.e., a pointer to an array of 5 chars.
These two expressions are of different types, but they're both
pointers, they both (in some sense) have the same value, and they
*probably* both have the same representation.
Since sscanf() takes a variable number and type(s) of arguments, the
compiler doesn't know what types are expected for the third and fourth
arguments in your call; it just blindly passes in whatever you
specify. It's your job to make sure you call it correctly. Since the
arguments you gave it were (probably) the same size and representation
as the correct arguments, it happened to work. (Passing something of
an incorrect type to sscanf() actually invokes undefined behavior;
working "correctly" is one of the many possible consequences.)
BTW, I believe there are real systems where char* and char (*p)5 would
have different representations, and your sscanf() call would fail.
The second thing if I want to jump one argument is it correct the
behaviour ?
year[5]
sscanf(str_date, "%*s/%4s", year);
and at last, at year will be placed the string terminator ('\0')
Yes, that should work (assuming the declaration is "char year[5]"
rather than "year[5]").