首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

这个为什么会提示段异常

2013-06-26 
这个为什么会提示段错误1 #include stdio.h2 #include stdlib.h3 #include string.h4 int main(int

这个为什么会提示段错误
  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中呢,还有他们的返回值并不是你想要的。

热点排行