【发布时间】:2014-04-10 23:54:33
【问题描述】:
我正在尝试将一些字符串写入文件。编译时没有警告,但是当我运行 a.out 时,它会出现段错误。不过,它确实创建了目标文件。我对 C 很陌生,所以我为我的格式和其他缺点道歉。这是我的代码:
#include<stdio.h>
int main (void)
{
FILE *fp_out;
char str1[]="four score and seven years ago our";
char str2[]="fathers broughy forth on this continent,";
char str3[]="a new nation, concieved in Liberty and dedicated";
char str4[]="to the proposition that all men are created equal.";
fp_out=fopen("my_file", "w");
if(fp_out!=NULL)
{
fprintf(fp_out,"%s\n", str1[100]);
fprintf(fp_out,"%s\n", str2[100]);
fprintf(fp_out,"%s\n", str3[100]);
fprintf(fp_out,"%s\n", str4[100]);
fclose(fp_out);
}
else
printf("The file \"my_file\" couldn't be opened\n");
return 0;
}
【问题讨论】:
-
str1[100]? NONE 字符串的长度接近 100 个字符,因此您正在访问尚未分配的内存。应该是fprintf(fp_out, "%s\n", str1) -
没有
strX[100] -
格式说明符
%s需要一个字符串变量或字符指针。例如,您传递的单个字符str1[100]不是有效地址。你想通过str1。 -
另外:你正在传递一个
char,其中fprintf需要一个char *。 IE。将其更改为strX不带数组下标 ([100]) -
StackExchange 网络不允许 5 岁儿童。
标签: c segmentation-fault printf