Lagastic Lagastic - 1 year ago 48
C Question

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:


(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:

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

Answer Source

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 reference1 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


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.

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