简体   繁体   中英

fscanf changes string variable?

I'm a beginner in programming and I'm currently learning C, but I've come across something that confuses me.

In my while loop i have:

char* bword = word
fscanf(fp, "%s", word);

Where word is a char[46], bword is a char* and fp is the file (a word dictionary in this case). I wanted to keep track of the word before it gets replaced when scanning fp. And it seemed logical to me to asign the word to a variable before it gets changed. But if I print bword after fscanf(fp, '%s", word) then it's changed to the new word! I don't really understand why and how.

If I do this:

bword = word;
printf("1.%s\n", word);
printf("2.%s\n", bword);
// scan the file for a for a word and store in word
fscanf(fp, "%s", word);
printf("3.%s\n", word);
printf("4.%s\n", bword);

I get these results in the command line:

1. 
2. 
3.a
4.a

(You don't see anything before 1 and 2 because the word was empty at the time). I also tried assigning word to something "bar" before the loop but then I got:

1.bar
2.bar
3.a
4.a

So how do I solve this? I don't want bword to change.

You need to understand that this

char *bword = word;

declares a pointer to the first element of the array word , which means that modifiying bword modifies word too, because bword is just a reference 1 to the real data location which is the array word

If you want bword and word to be independent of each other then make bword an array so it's stored in a different location, like this

char bword[SOME_REASONABLE_SIZE];

from here you can call fscanf() and pass the appropriate array and the result will be the one you expected before.

Notice, that when you pass the array to fscanf() , essentially you are passing a pointer to the first element of it, just what your bword was in the first place.


1 A reference in a general sense, not in c++ sense.

First you must learn about pointers (you can see tutorialspoint ).
Then you find out array is a pointer to a memory so when you assigning them you just assign addresses so if one of them change other one is also changed. if you want to copy strings you can not assign then you must copy them and you can use strcpy() function. as it man page says it have following syntax:

char *strcpy(char *dest, const char *src);

The strcpy() function copies the string pointed to by src, including the terminating null byte ('\\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM