Home > Mobile >  I have trouble to copy the string from buffer to a new array which contains strings (char *)
I have trouble to copy the string from buffer to a new array which contains strings (char *)

Time:04-04

I am trying to use `strcpy' to copy the strings in buffer to a new array that contains strings (char *). I always received error message of seg fault. But I don't know why that happen.

char buffer[1024];
FILE *fp1;
fp1 = fopen("input.txt", "r");
char* array[file_row];
int index = 0;

while (fgets(buffer, sizeof(buffer), fp1) != NULL) {
    strcpy(array[index  ], buffer);
    printf("%s", buffer);
}

fclose(fp1);
return 0;

This is my part of codes, I hope that can provide enough information about my problem. I can't allocate memory for that array since its size is fixed, and I think I don't need to allocate each slot in array since strcpy did that for me. Also, I can print the content in buffer, so I think buffer worked well. Then I am not sure why this error happened. Can someone help me please?

CodePudding user response:

THis

char* array[file_row];

is an array of pointers that point nowhere. In order to strcpy to them they have to point to a section of memory large enough to take the string. The easy solution is to use strdup it will allocate the memory and copy the string for you

instead of

  strcpy(array[index  ], buffer);

do

  array[index  ] = strdup(buffer);

(on windows you need _strdup)

  • Related