-1

I'm having a lot of difficulty doing this! What I do is get the first line to initialize an array of pointers, then want to point those blocks to variables that contain the string from the text document. However; even when I read all the values into the array they are all pointing to the same variable which changes as the file is being read. Is there way I can copy those values into the array without them all pointing to the changing line as the file is being read?

int main(void){
FILE * fp;
char line[256];
int i = 0;
int digit = 0;

fp = fopen("testfile","r");

if(fp == NULL){
    printf("Cannot Open File");
}
fgets(line,sizeof(line),fp);
digit = atoi(line);
printf("digit = %d\n",digit);
char *rest[digit];
while(!feof(fp)){
    while (i < digit){
        fgets(line,sizeof(line),fp);
        fgets(line,sizeof(line),fp);
        printf("line = %s",line);
        char arr[sizeof(line)+1];
        strcpy(arr,line);
        rest[i] = arr;
        printf("restaurant = %s",rest[i]);
        i++;
    }

the text file is as follows:

6
Outback Steakhouse
Red Robin
Max & Erma’s
Chipotle
Panera
BW3
8
Stephanie 5 3 2 4
Chris 4 6 5 1
Peter 5 2 4 1
Josh 1 4 3 6
Jessica 5 2 3 4
Al 6 4 2 3
Adam 5 1 3 2
Eric 1 4 3 5
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
user3260745
  • 137
  • 2
  • 14
  • `rest[i] = arr;` That just points each entry in the array to the same buffer. So of course the result is the same string for every entry. You need to allocate seperate memory buffers for each string. – kaylum Feb 08 '16 at 19:56
  • 1
    Why are you calling fgets twice after the while (i < digit). You will be throwing half you data away. – Robert Jacobs Feb 08 '16 at 19:57
  • Have a look at http://stackoverflow.com/a/19174415 and http://stackoverflow.com/a/4237107 – Robert Harvey Feb 08 '16 at 19:57
  • 1
    there are many logic errors... I think the big problem is the knowledge of c – GMG Feb 08 '16 at 20:02
  • There are spaces between each line in the text file, therefore to jump over the spaces I call it twice. I originally had it so if the length of the line was < 1 then just skip the entry, but because line is initialized with 256 'slots' I didn't know how else to get around this. – user3260745 Feb 08 '16 at 20:06

1 Answers1

1

You need to copy the values into dynamically allocated memory. strdup will do. Replace:

    char arr[sizeof(line)+1];
    strcpy(arr,line);
    rest[i] = arr;

With:

    rest[i] = strdup (line);

Also you call fgets twice.

Additionally, when line is too long, it will be not zero terminated. To make it safe always assign zero at the end of line.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43