字符指針變量和字符數(shù)組都可以處理字符、字符串,但是兩者卻有著本質(zhì)的區(qū)別。今天用到就把所有的總結(jié)一下,以供大家參考!
1、字符數(shù)組初始化及賦值
char c_a[] = {"songjinshi"};//正確
watch window 顯示的:
c_a[0]='s'
c_a[1]='o'
c_a[2]='n'
c_a[3]='g'
c_a[4]='j'
c_a[5]='i'
c_a[6]='n'
c_a[7]='s'
c_a[8]='h'
c_a[9]='i'
c_a[10]='\000'
char c_a[] = {'s','o'};//正確
c_a[0] ='s'
c_a[1]='o'
char c_a[] = "songjinshi";//正確
c_a[0] ='s'
c_a[1] ='o'
c_a[2] ='n'
c_a[3] ='g'
c_a[4] ='j'
c_a[5] ='i'
c_a[6] ='n'
c_a[7] ='s'
c_a[8] ='h'
c_a[9] ='i'
c_a[10] ='\000'
char c_a[10] = "songjinshi";
c_a[0] ='s' c_a[1] ='o' c_a[2] ='n' c_a[3] ='g' c_a[4] ='j' c_a[5] ='i' c_a[6] ='n' c_a[7] ='s' c_a[8] ='h' c_a[9] ='i'
char c_a[11];
c_a = "songjinshi";//錯誤,c_a是一個指針常量不能直接賦值
c_a++;//錯誤,c_a是一個指針常量
char c_a[11];
for(i=0;i<11;i++)
scanf("%c",c_a+i);//正確
char c_a[11];
scanf("%s",c_a);//正確
char c_a[11];
strcpy(c_a,"songjinshi");//正確
2、字符指針初始化及賦值
char* c_p = "songjinshi";//正確
char* c_p = 0;//正確,指針變量值為0,字符串長度為0,即字符指針指向一個空字符串
char*c_p = "songjinshi";
c_p = "song";//正確,改變字符指針指向的字符串,即改變字符指針變量的值(地址)
c_p++;//正確,移動指針
printf("%s",c_p);//輸出ongjinshi
char* c_p;
scanf("%s",c_p);//錯誤,c_p是一個字符指針但是沒有指向有效的內(nèi)存地址(空間)
char* c_p = "song";
*c_p = 'z';//錯誤,c_p指向的是常量數(shù)據(jù)區(qū)(常量數(shù)據(jù)表——靜態(tài)存儲區(qū)),不能更改里面的內(nèi)容
char* c_p = "songjisnhi";
strcpy(c_p,"zhangdi");//錯誤,c_p指向常量數(shù)據(jù)區(qū),無法更改
聯(lián)系客服