tags:

views:

112

answers:

3

char first[10];

char second[10];

What does fscanf(fr,"%s %s\n",first,second); do when first string is too long?

can I use just char *first without malloc? and the pointer will show to the string?

+3  A: 

You can use a width (i.e. "%9s") to restrict the size of the string. For example, see Microsoft's documentation.

Using a pointer without initializing it to anything is a sure way to get your program to crash, or otherwise behave badly.

Mark Ransom
but I can have smaller string than 10. in that case I wouldn't get it all.
feiroox
From the documentation: "Fewer than width characters may be read if a whitespace character (space, tab, or newline) or a character that cannot be converted according to the given format occurs before width is reached."
Mark Ransom
One more thing - the width given to fscanf should be one less than the size of the string, to allow for the null terminator. I'll update my example.
Mark Ransom
+1  A: 

When the first string is too long, you run into a problem of a buffer overflow.

As for the second part of your question, if you do not use malloc, then then it will be pointing to garbage memory. Its possible that the string will stay there for a while, but its not guaranteed, and if that memory segment is used by something else you will lose your string.

yx
+2  A: 

If you are using glibc, you can solve both issues in one shot - use %as format specifier.

It will automatically allocate string big enough to hold the content.

Like this:

char *first, *second;

scanf(fp, "%as %as\n", first, second);

Note: This is GNU extension!

qrdl
hi thank you. it's a pity that it's not under windows :)
feiroox