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

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章