C-字符串数组的动态内存分配问题

C- Dynamic memory allocation for an array of strings problem

我正在做一个项目,我需要动态分配一个字符串数组。每个字符串都是 csv 文件中的一行。问题是在最终数组上,数组中除最后一个字符串之外的每个字符串都是乱码。我仍在学习指针,我无法弄清楚发生了什么。

CSV 文件:

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


代码:

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] = '[=11=]';
        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);



输出:

 P☺3┌↓☻
░x3┌↓☻
(null)
AntonioSilva,14112000,12,E,1,89.4

输出的最后一行是唯一正确的

您正在为每一行重新分配外部数组

while(fgets(buffer, MAXCHAR, fp) != NULL) {
    strings = malloc(lines_count * sizeof(char *)); <<<<=====
    length = strlen(buffer);
    buffer[length] = '[=10=]';
    strings[ctrl] = malloc(length * sizeof(char));
    strcpy(strings[ctrl], buffer);
    ctrl++;
}

这应该只做一次,而且你需要为字符串 +1

strings = malloc(lines_count * sizeof(char *));

while(fgets(buffer, MAXCHAR, fp) != NULL) {
    length = strlen(buffer);
    //buffer[length] = '[=11=]'; <<< === not useful since strlen tells you the location of terminating null
    strings[ctrl] = malloc((length + 1) * sizeof(char)); <<<=== +1
    strcpy(strings[ctrl], buffer);
    ctrl++;
}