[英]Segmentation fault when writing char array to file in C
當我運行以下代碼時,我在fprintf(outfile, "%s", inputline[j]);
處收到“分段錯誤” .
我無法理解錯誤的原因。 我對 C 比較陌生,有人可以幫我解決這個錯誤嗎?
void test(char *inputline) {
FILE *outfile = fopen("results.txt", "w");
if (!outfile) {
perror("Error while opening file: ");
} else {
for (int j = 0; j < 20; ++j) { // I only want to be write the first 20 characters to the file that is why I have the iteration till only 20 and added [j], is that correct way to do it?
fprintf(outfile, "%s", inputline[j]);
}
}
}
//Function call
...
char inputline[40] = "hello world 123 456"; //passed to the function above
test(inputline);
格式說明符%s
在
fprintf(outfile, "%s", inputline[j]);
需要一個char *
變量,但您實際上傳遞的是一個char
( inputline
數組的第 j個元素)。
發生段錯誤的原因是fprintf
試圖“訪問”由傳遞的字符指向的 memory 位置。 由於它很可能是無效地址,因此操作系統會抱怨試圖在分配給您的應用程序的空間之外訪問 memory。
您可以通過 char 打印到文件 char ,保留 for-loop 並使用%c
格式
for(int j=0; j<20; ++j)
{
fprintf(outfile, "%c", inputline[j]);
}
或者打印整個字符串,保持%s
格式,傳遞整個數組並去掉 for 循環:
fprintf(outfile, "%s", inputline);
注意:無論如何,在第一種情況下,將寫入 20 個字符。 在第二種情況下,“length+1”字符是因為字符串終止符'\0'
。
代碼中導致分段錯誤的錯誤是您將char
值inputline[j]
傳遞給%s
參數的printf
,它需要一個字符串指針。 這具有未定義的行為。
要最多寫入字符串的前 20 個字符,您可以使用%.20s
作為格式說明符。 也不要忘記關閉文件:
void test(const char *inputline) {
FILE *outfile = fopen("results.txt", "w");
if (outfile == NULL) {
perror("Error while opening file: ");
} else {
// print at most 20 bytes from inputline
fprintf(outfile, "%.20s\n", inputline);
fclose(outfile);
}
}
請注意,如果需要,此最大計數可以是具有%.*s
格式的變量:
int limit = 20;
fprintf(outfile, "%.*s\n", limit, inputline);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.