I have a really weird problem with fgets() in C. Below is the code I’m working with.
FILE* conf_file;
char array[20];
conf_file=fopen("configuration","r");
if (!conf_file) printf("There is not conf file");
while(!feof(conf_file)){
// if( feof(conf_file)) break;
fgets(array,20,conf_file);
//printf("%s",array);
if (!read_id_flag){
labris_id=atoi(array);
read_id_flag=1;
printf("%d\n",id);
continue;
}
protocol_array[protocol_index]=array;
// printf("%s %s",array,protocol_array[protocol_index]);
protocol_index++;
}
int i;
for(i=0;i<10;i++){
printf("%s",protocol_array[i]);
}
fclose(conf_file);
Well, in the while scope if I try to print the protocol_array it works perfectly. But if I try to print the array after the while scope, it prints only the last line of the array, 6 times (6 is number of lines in the file).
Any idea is appreciated. Thanks in advance.
char* protocol_array[];can’t contain any data directly, other than a pointer to the allocated memory.You should either define
protocol_arrayaschar protocol_array[20][6];, allocating storage for 6 lines of string with length 20 and strcpy like this:or allocate the memory via
malloc:Note that in the latter case you should
freeany allocated memory when you’re done with it: