0

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!

Gerhard
  • 6,850
  • 8
  • 51
  • 81
  • 1
    "but when I copy string to array" is a falsify. `urls[index++] = url;` copies a pointer, not a _string_. – chux - Reinstate Monica Mar 02 '22 at 06:13
  • @chux-ReinstateMonica How do I copy the string then? – Kerelos Tawfik Mar 02 '22 at 07:01
  • To copy a string, research `strcpy()`. – chux - Reinstate Monica Mar 02 '22 at 17:03
  • I am doing that but now I get this ==10731== Process terminating with default action of signal 11 (SIGSEGV) ==10731== Access not within mapped region at address 0x4844000 ==10731== at 0x4838DC8: strcpy (vg_replace_strmem.c:512) ==10731== by 0x109898: generateInvertedIndex (invertedIndex.c:101) ==10731== by 0x1092B4: test1 (testInvertedIndex.c:36) ==10731== by 0x109244: main (testInvertedIndex.c:23) – Kerelos Tawfik Mar 03 '22 at 05:09

1 Answers1

1

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.

tia
  • 9,518
  • 1
  • 30
  • 44
  • 1
    Thank you that makes a lot of sense. So how would I get it to copy the contents then? Is this where I would use strcpy instead? – Kerelos Tawfik Mar 02 '22 at 06:34
  • 1
    `strcpy` can be used, but you also need to prepare buffer for that too. Another different problem but a critical one with your code is buffer overflow because `url` might be too small to hold the string. Check https://stackoverflow.com/questions/1621394/how-to-prevent-scanf-causing-a-buffer-overflow-in-c for more information about that. – tia Mar 02 '22 at 07:22
  • Why do I need to prepare a buffer for strcpy? How would I go about it? – Kerelos Tawfik Mar 02 '22 at 08:06