我正在做一個專案,我需要動態分配一個字串陣列。每個字串都是 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] = '\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);
輸出:
P?3┌↓?
?x3┌↓?
(null)
AntonioSilva,14112000,12,E,1,89.4
輸出的最后一行是唯一正確的
uj5u.com熱心網友回復:
你在每一行重新分配你的外部陣列
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 ;
}
這應該只做一次,而且你需要為字串 1
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 ;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463126.html
上一篇:廣義外積-函式接受lambda
