-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
5
  • 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. Commented Feb 8, 2016 at 19:56
  • 1
    Why are you calling fgets twice after the while (i < digit). You will be throwing half you data away. Commented Feb 8, 2016 at 19:57
  • Have a look at stackoverflow.com/a/19174415 and stackoverflow.com/a/4237107 Commented Feb 8, 2016 at 19:57
  • 1
    there are many logic errors... I think the big problem is the knowledge of c Commented Feb 8, 2016 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. Commented Feb 8, 2016 at 20:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't know about OP, but that answer worked for me! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.