天天看點

char *與char []類型的差別

參考文章:char *s 和 char s[] 的差別小結

char *s1 = "hello";

char s2[] = "hello";

【差別所在】

char *s1 的s1是指針變量,而指針是指向一塊記憶體區域,它指向的記憶體區域的大小可以随時改變,但當指針指向常量字元串時,它的内容是不可以被修改的,否則在運作時會報錯。

char s2[]的s2 是數組對應着一塊記憶體區域,其位址和容量在生命期裡不會改變,隻有數組的内容可以改變

【記憶體模型】

       +-----+     +---+---+---+---+---+---+

   s1: |  *======> | h | e | l | l | o |\0 |

       +-----+     +---+---+---+---+---+---+

       +---+---+---+---+---+---+

   s2: | h | e | l | l | o |\0 |

       +---+---+---+---+---+---+

示例代碼:

#include <iostream>

int main()
{
	char *s1 = "hello";
	char s2[] = "hello";
	char *s3 = s2;				//★注意這句必須要★
	char **s4 = &s3;			//s2(char[])要用兩步才能完成指派 
	char **s5 = &s1;			//s1(char*) 隻需一步
	char(*s6)[6] = &s2;			//&s2等價于char(*)[6]:指向包含6個char型元素的一維數組的指針變量

	printf("s1=[%s]\n", s1);
	printf("s2=[%s]\n", s2);
	printf("s3=[%s]\n", s3);
	printf("s4=[%s]\n", *s4);	
	printf("s5=[%s]\n", *s5);
	printf("s6=[%s]\n", s6);	

	printf("\n size of s1: %d \n", sizeof(s1));
	printf("\n size of s2: %d \n", sizeof(s2));

	system("pause");

	return 0;
}
           

運作結果如下:

char *與char []類型的差別

注:字元串比較不能使用等于号,隻能使用strcmp函數;相同則傳回0,反之傳回非零值。

#include<iostream>
#include<string>

using namespace std;

char str[20] = { "hello hdu" };
char *pstr;

int main()
{
	pstr = str;
	cout << *str << endl;		// h
	cout << *pstr << endl;		// h
	*pstr++ = 'Y';			
	cout << *str << endl;		// Y
	cout << *pstr << endl;		// e
	cout << *(pstr-1) << endl;	// Y
	cout << *(pstr--) << endl;	// e
	system("pause");
	return 0;
}