thr*_*six 1 c printf segmentation-fault
我正在尝试将一些字符串写入文件.编译时没有任何警告,但是当我运行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;
}
Run Code Online (Sandbox Code Playgroud)
你应该阅读手册fprintf().
int fprintf(FILE *stream, const char *format, ...);
Run Code Online (Sandbox Code Playgroud)
在您正在使用的格式字符串中%s,这意味着您将传递fprintf()一串字符.
这是一串字符:
char str1[]="four score and seven years ago our";
Run Code Online (Sandbox Code Playgroud)
这是您打印字符串的方式:
fprintf(fp_out,"%s\n", str1);
Run Code Online (Sandbox Code Playgroud)
你在这里想做什么:
fprintf(fp_out,"%s\n", str1[100]);
Run Code Online (Sandbox Code Playgroud)
是打印在101 日的性格str1,这是没有这么长,所以你试图访问超出了你的阵列拥有什么存储方式......更何况你传递一个字符格式字符串预期导致串UB.
| 归档时间: |
|
| 查看次数: |
10151 次 |
| 最近记录: |