Home > Software design >  fscanf reads string but when I copy string to array it modifies the whole array
fscanf reads string but when I copy string to array it modifies the whole array

Time:03-02

I have this code. This is the file content

nasa.txt
news1.txt
file11.txt
mixed.txt
planets.txt
file21.txt
info31.txt

This is the code

    FILE *fp = fopen(collectionFilename, "r");

    char url[MAX_WORD   1];
    char *urls[MAX_WORD   1];

    while(fscanf(fp, "%s", url) == 1){
        urls[index  ] = url;
    }

    for(int i = 0; i < index; i  ){
        printf("%s\n", urls[i]);
    }
    fclose(fp);

I want the code to read in the file names and store them into my urls array. However my printf statement at the end prints info31.txt 7 times and I'm a bit confused as to why this happens.

Thank you!

CodePudding user response:

From your code there are two steps in the loop

  1. fscanf(fp, "%s", url) will read string and write the string to url
  2. urls[index ] = url; will assign urls[index] to point to url and increase index by one

The key point is that in step 2, you just repeat the same thing to every elements in urls -- pointing them to url, which is why you get the same URL from urls. You never copy the characters from url to somewhere else and fscanf just keep using the same buffer for input in every iteration.

  •  Tags:  
  • c
  • Related