1. 程式人生 > >段錯誤 (核心已轉儲) 字元指標 ubuntu

段錯誤 (核心已轉儲) 字元指標 ubuntu

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

報錯:

[email protected]:~/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);
                   ^
[email protected]
:~/code$ ./hex_to_8 12345 段錯誤 (核心已轉儲) [email protected]:~/code$
原因:

char *p = " "這樣定義後,相當於p變為常量指標,p所指向的內容不能被修改.

可以換成陣列的 char p[]=" "

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