段錯誤 (核心已轉儲) 字符指針 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;
    
}


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