#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;
}