Re: SSCANF
- From: "Mike Wahler" <mkwahler@xxxxxxxxxxxx>
- Date: Tue, 03 Jan 2006 19:24:45 GMT
"Superfox il Volpone" <atari@xxxxxxxx> wrote in message
news:1136310085.816491.322760@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> Hello
>
> I have some problem with sscanf, I tryed this code but it doesn't works
> :
>
> char* stringa = "18/2005"
"18/2005" is a string literal. Any attempts to modify
any of its characters produces undefined behavior.
> char mese[3]; char anno[5];
> int i_letture;
>
> i_letture = sscanf(stringa, "%2s/%4s", &mese, &anno);
This gives undefined behavior. You're trying to modify
a string literal.
Also, since 'mese' and 'anno' are arrays, their names
in this context will evalutate to pointers to their
first element. So e.g. use 'mese', not '&mese'.
%s must match with type 'char*'. The expression &mese
does not have that type. Its type is (*)[3] (pointer to
array of three char). Not the correct type.
> mese[2] = anno[4] = '\0';
'sscanf()' already applies the string terminator for you
(in the proper location)
Also (disregarding for now the string literal problem)
note that if the size of data stored by 'sscanf()' is
less than the size of the array, your arbitrary placement of
'\0' as the last array element will not terminate the string
properly (there will be 'garbage' between the data and the
terminator).
>
> The values ar random and I don't understand the motive
You don't understand how 'sscanf()' works, or how arrays
and pointers work.
> I tryed either this variant :
>
> char* porka_vakka = strchr(stringa, '/');
> *porka_vakka = '\0'; // but either ' ' e '\n'
There are two possible results of these two lines, both of
which are undefined behavior:
1) The character '/' is not found in the string (which
causes 'strchr()' to return NULL), in which case you
try to dereference a NULL pointer. Undefined behavior.
2) The character '/' is found (and 'strchr()' returns its
address. You then try to modify it, but it's part of
a string literal. Undefined behavior.
> i_letture = sscanf(stringa, "%s", &mese);
More undefined behavior. Attemt to modify string literal.
Wrong data type used with '%s'.
Finally, even if you do have writable storage for 'sscanf()'
note that you have no protection against the data overflowing
your array. Look up the 'width' flag for sscanf() format
specifiers.
>
> But neither this works...
>
> Could anyone help me ?
I think the best advice I can give is to recommend you get
some good textbooks.
http://www.accu.org/bookreviews/public/reviews/0sb/beginner_s_c.htm
-Mike
.
- Follow-Ups:
- Re: SSCANF
- From: Emmanuel Delahaye
- Re: SSCANF
- From: Christopher Benson-Manica
- Re: SSCANF
- From: Michael Mair
- Re: SSCANF
- References:
- SSCANF
- From: Superfox il Volpone
- SSCANF
- Prev by Date: Re: Segmentation fault - interesting problem with array
- Next by Date: Re: need information on the following items
- Previous by thread: Re: SSCANF
- Next by thread: Re: SSCANF
- Index(es):
Relevant Pages
|