I'm working on a project and I need to dynamically allocate an array of strings. Each string is a line from a csv file. The problem is that on the final array, every string of the array but the last one is gibberish. I'm still learning pointers and I can't figure out what's happening.
CSV File:
ZeManel,10032003,7,B,12,50
AntonioSilva,03102002,8,A,23,15
AlbinoFerreira,25122001,9,C,2,31
AntonioSilva,14112000,12,E,1,89.4
Code:
void sorting(){
FILE *fp = fopen("C://Users//G512L//CLionProjects//ProjetoPPP//active_students.csv", "r"), *fp_temp = ("C://Users//G512L//CLionProjects//ProjetoPPP//active_students.csv", "w");
char str[MAXCHAR], **strings, buffer[MAXCHAR];
int lines_count = 0, ctrl = 0, length = 0;
if(fp == NULL) {error_op_fl();}
else{
while(fgets(str, MAXCHAR, fp) != NULL){
lines_count ;
}
rewind(fp);
while(fgets(buffer, MAXCHAR, fp) != NULL) {
strings = malloc(lines_count * sizeof(char *));
length = strlen(buffer);
buffer[length] = '\0';
strings[ctrl] = malloc(length * sizeof(char));
strcpy(strings[ctrl], buffer);
ctrl ;
}
for(int x = 0; x < lines_count; x ){
printf("%s\n", strings[x]);
}
}
free(strings);
Output:
P☺3┌↓☻
░x3┌↓☻
(null)
AntonioSilva,14112000,12,E,1,89.4
The last line of the output is the only one correct
CodePudding user response:
You are reallocating your outer array on every line
while(fgets(buffer, MAXCHAR, fp) != NULL) {
strings = malloc(lines_count * sizeof(char *)); <<<<=====
length = strlen(buffer);
buffer[length] = '\0';
strings[ctrl] = malloc(length * sizeof(char));
strcpy(strings[ctrl], buffer);
ctrl ;
}
That should be done only once, plus you need 1 for the string
strings = malloc(lines_count * sizeof(char *));
while(fgets(buffer, MAXCHAR, fp) != NULL) {
length = strlen(buffer);
//buffer[length] = '\0'; <<< === not useful since strlen tells you the location of terminating null
strings[ctrl] = malloc((length 1) * sizeof(char)); <<<=== 1
strcpy(strings[ctrl], buffer);
ctrl ;
}