您的位置:首页 > 其它

段错误 (核心已转储) 字符指针 ubuntu

2015-03-15 20:31 387 查看
#include<stdio.h>
int main()
{
char *p="";
scanf("%s",p);
printf("%s",p);
return 0;

}

报错:

smart@smart-K45VD:~/code$ g++ hex_to_8.cpp -o hex_to_8
hex_to_8.cpp: In function ‘int main()’:
hex_to_8.cpp:4:13: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
char *p="";
^
hex_to_8.cpp:6:19: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘int’ [-Wformat=]
printf("%s",*p);
^
smart@smart-K45VD:~/code$ ./hex_to_8
12345
段错误 (核心已转储)
smart@smart-K45VD:~/code$

原因:
char *p = " "这样定义后,相当于p变为常量指针,p所指向的内容不能被修改.

可以换成数组的 char p[]=" "

#include<stdio.h>
int main()
{
char p[]="";
scanf("%s",p);
printf("%s",p);
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  错误日志