这个为什么会提示段错误
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 int main(int argc,char *argv[])
5 {
6 char buf[128];
7 memset(buf,'\0',128);
8 char *ptr=NULL;
9 printf("please input strings less than 128 chars:\n");
10 fgets(buf,128,stdin);
11 printf("This is the output by puts:%s",(char *)puts(buf));
12 printf("This is the output by fputs:%s",(char *)fputs(buf, stdout));
13 return 0;
14 },
这个为什么会提示段错误,我输入的字符小于128个啊 fputs?puts
[解决办法]
问题出在puts和fputs返回的是int类型,被你强制转为char*了。
例如:
printf("This is the output by puts:%s",(char *)puts(buf));
应该改为:
printf("This is the output by puts:");
puts(buf);
[解决办法]
出现段错误,一般是非法访问只读内存区域。我认为是LZ对函数使用有误,puts和fputs完全可以单独使用,为什么要放到printf中呢,还有他们的返回值并不是你想要的。