任務是從特定檔案中讀取前 20 行并將它們格式化為僅使用特定部分,下一步是將這些格式化的字串存盤在動態陣列中(char ** str| 指向指標的指標),將其發送到函式并用上述功能列印出來
這是主要代碼:
int main(int argc, char* argv[]){
FILE* file = fopen("./passwd.txt", "r"); // open file
if (!file)
{
perror("Error opening file");
return 1;
}
char line [MAXCHARS];
int counter = 0;
char ** str;
str = malloc(20 * sizeof (char*));
while (fgets(line, MAXCHARS, file) && counter < 20) {
char * position;
if ((position = strchr(line,':'))){
char * end_char;
*position = 0; //setting here the value 0, will terminate the string line (first column)
if((position = strchr( position,':')) && (end_char = strchr( position,':'))){ //increment the position to skip the second column
*end_char = 0; //set the value 0 to end_char to terminate the string pointed by position
char * temp_str = "\0";
sprintf(temp_str, "{%d} - {%s}\n", atoi(position), line ); //concatenate line and userID into one string and store it into a temporary string
*(str counter) = malloc(sizeof (char) * strlen(temp_str)); //set the memory space for the temp_string into the array
*(str counter) = temp_str; //copy the string into the array
}
}
counter ;
}
printArray(str);
fclose(file);
if (line)
free(line);
return 0;
}
這是列印功能:
void printArray(char ** array){
for(int i = 0; i < 20; i ){
printf("%s",*(array i));
free(*(array i));
}
free(array);
}
我找不到錯誤,代碼編譯
Process finished with exit code -1073741819 (0xC0000005)
所以至少它可以編譯,我認為這只是我的指標處理技巧的一個問題,但我無法找到錯誤。
有人能幫我嗎?
uj5u.com熱心網友回復:
您的程式中有 3 個錯誤:
使用尚未分配的 temp_str。
char * temp_str = "\0"; sprintf(temp_str, "{%d} - {%s}\n", atoi(position), line );將
temp_str本地指標的地址保存到str counter并在指標超出范圍后使用printArray=> 未定義行為line不是指標,不能使用freeif (line) { free(line); }
讓我們試試這個。https://godbolt.org/z/7KPfnTEMY我更正了這些點
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/446142.html
上一篇:我需要了解這些C指標的行為
下一篇:我的輔助函式回傳一個空字串
