I've a function that reads N lines from a text file and save them into a first array (array_slave
). After that, I'm trying to save the last for element of this array into another array (char *last_4_samples[128]
). First question: is it right? Am I doing it right?
char *retrieve_last_4_samples(char slave[], char file_path[]){
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen(file_path, "r");
if (fp == NULL)
exit(EXIT_FAILURE);
char *array_slave[128];
int i = 0;
while ((read = getline(&line, &len, fp)) != -1)
{
if (strstr(line, slave) != NULL)
{
array_slave[i] = malloc(sizeof(*line)*len);
strcpy(array_slave[i], line);
i ;
}
}
int number_of_samples = array_length(array_slave);
char *last_4_samples[4];
for(int i=0;i<4;i ){
*(last_4_samples i) = *(array_slave i);
}
for(int i=0;i<number_of_samples;i )
free(array_slave[i]);
return last_4_samples;
}
Now, in the main function, I'm trying to assign the pointer last_4_samples
to another pointer, so that I can use it into the main.
char *ptr[128];
ptr = retrieve_last_4_samples(SLAVE_1,FILE_PATH);
main.c:50:9: error: assignment to expression with array type
50 | ptr = retrieve_last_4_samples(SLAVE_1,FILE_PATH);
What am I doing wrong?
CodePudding user response:
There are at least two mistakes:
free(array_slave[i]);
destroys memory for all elements of the array, including last 4 samples. So, whatever is in thelast_4_samples
is destroyed as well, because you used pointers in assignments:*(last_4_samples i) = *(array_slave i);
As a result the last last_4_samples
becomes invalid even before return.
- you are returning
last_4_samples
which is declared as a local array on the function stack. This will become invalid in any case after return from the function.
To follow your scheme you need to
- duplicate your string, e.g.,
*(last_4_samples i) = strdup(*(array_slave i))
- avoid declaring arrays for the return:
char **last_4_samples = malloc(sizeof(char*), 4);
now you can return the value of the last_4_samples pointer. Of course, you will need to free it later, but in two steps:
for(int i = 0; i < 4; i )
free(returned_samples[5]);
free(returned_samples);