Reputation: 1078
I have the following code in which I'm reading lines from a file and want to save them using a character pointer array. As I'm using one buffer inside my file read loop all my pointers in the character array end up pointing towards the last line read from file as the last line is the one that is currently held in the buffer when the loop terminates. How can I store them such that each pointer in the character array points to different char arrays in the order they were read.
int num_clients_to_start = 0;
char *token1, *token2, *str;
FILE* fp;
char bufr[256];
char testchar[255] = {};
char *start_client[10];
while(fgets(bufr, 256, fp) != NULL){
if(bufr[0] == '#'|| bufr[0] == '\n')
continue;
str = bufr;
token2 = ""; /* initializing an empty token 2 */
for(str = bufr; ;str = NULL){
token1 = strtok(str, " ");
if(strcmp(token2, "client_name") == 0){
sprintf(testchar,"%s", token1);
start_client[num_clients_to_start] = testchar;
num_clients_to_start++;
}
token2 = token1;
if(str == NULL){
break;
}
}//end of for loop
}//end of while loop
printf("client1 = %s client2 = %s client3 = %s",start_client[0],start_client[1],start_client[2]);
My input file is the following:
client_name abc
client_name def
client_name xyz
And print statement outputs:
client1 = xyz
client2 = xyz
client3 = xyz
Upvotes: 1
Views: 3958
Reputation: 41036
Note that start_client[0]
, [1]
, [2]
are all pointers to the last string (readed by fgets
)
Use strdup in order to allocate them:
start_client[num_clients_to_start] = strdup(testchar);
As strdup
can be an external identifier, use a prototype
#include <string.h>
char *strdup(const char *s);
And don't forget to free()
at the end
Upvotes: 3
Reputation: 409364
You assign the same pointer to all entries in the start_client
array. The array testchar
will get different contents, but the pointer to it will always be the same. You might want to make start_client
an array of arrays of char
, and copy the string instead.
Like
char start_client[10][256];
And
strcpy(start_client[num_clients_to_start++], token1);
Upvotes: 1