const char * 、char const *、 char * const 三者的區別
C/C++ 中關於以下三種定義:
const char *ptr;
char const *ptr;
char * const ptr;
現整理三者之間的區別與聯絡。一、const char *ptr;
定義一個指向字元常量的指標,這裡,ptr是一個指向 char* 型別的常量,所以不能用ptr來修改所指向的內容,換句話說,*ptr的值為const,不能修改。但是ptr的宣告並不意味著它指向的值實際上就是一個常量,而只是意味著對ptr而言,這個值是常量。實驗如下:ptr指向str,而str不是const,可以直接通過str變數來修改str的值,但是確不能通過ptr指標來修改。
gcc編譯報錯資訊:
註釋掉16行ptr[0] = 's';執行正常,執行結果為:
hello world
gello world
另外還可以通過重新賦值給該指標來修改指標指向的值,如上程式碼中取消7、18行的註釋,執行結果為:
hello world
good game!!
二、char const *ptr;
此種寫法和const char *等價,大家可以自行實驗驗證。
三、char * const ptr;
定義一個指向字元的指標常數,即const指標,實驗得知,不能修改ptr指標,但是可以修改該指標指向的內容。實驗如下:
gcc報錯資訊:
註釋掉17行程式碼執行正常,執行結果為:
hello world
sello world
以上轉自:https://blog.csdn.net/SilentOB/article/details/76994618
個人總結:
const char *ptr==char const *ptr; 可以直接改變指標指向,但不能直接改變指標指向的值;*ptr=*ss;
char *const ptr; 可以直接改變指標指向的值,但不能直接改變指標指向;ptr[0]='s';
但兩者都可以通過改變所指向的指標的內容,來改變它的值。
int main()
{
char str[] = "hello world";
char sec[] = "code world";
cout << ptr1 << endl;
strcpy(str,"hi world");
cout << ptr1 << endl;
ptr1 = sec;//直接改變指標指向
cout << ptr1 << endl;
sec[0] = 'o';
cout << ptr1 << endl;
ptr1[0] = 'a';//直接改變指標指向的值,報錯
char ss[] = "good game";
char *const ptr2 = ss;
cout << ptr2 << endl;
ptr2[0] ='a';//直接改變指標指向的值
cout << ptr2 << endl;
strcpy(ptr2, "last");
cout << ptr2 << endl;
ss[0] = 'z';
cout << ptr2 << endl;
ptr2 = sec;//直接改變指標指向,報錯
system("pause");
}