天天看點

指針數組,數組指針,字元串與指針指針數組與數組指針指針數組字元串與指針

指針數組與數組指針

在研究指針數組與數組指針的時候,遇到了這個困惑,後面解答。

void test02()
{
	char* p1[4] = { "節","日","快","樂" };
	char c[4] = { 'A','B','C','D' };
	char *P2[4];//指針數組
	for (int j = 0; j < 4; j++)
	{
		P2[j] = &c[j];
		cout << *P2[j] << endl;
	}
	for (int i = 0; i < 4; i++)
	{
		//指針數組裡面存放的不應改是位址嗎?為什麼輸出的竟然是字元串
		//覺得應該像上面那樣,加上解引用*,但是會出錯
		//這裡涉及char*與char定義數組的問題
		printf("%s\n", p1[i]);
	}
}
           

指針數組

指針數組是數組,即一個數組中,每個元素都是指針;

void test05()
{
	int value1 = 1;
	int value2 = 2;
	int value3 = 3;
	//指針數組,存放位址
	int* Ary[3] = {&value1,&value2,&value3};
	//注意這一行和最後一行的差別;
	cout << *Ary[0] << endl;
	char* s1 = "hello";
	char* s2 = "world";
	char* s3 = "haha";
	char* Ary2[3] = {s1,s2,s3};
	//直接輸出位址,但是出來的卻是内容。
	//char*指針可以當字元串使用
	cout << Ary2[0] << endl;
}
           

#數組指針

本質上應該是一個指針,指向數組的指針。

void test06()
{
	對應的不是1,2,3,4的值,而是ASCII碼中的值
	//若要輸出數字1,2,3,4,應該寫成 char s[4]={'1','2','3','4'}
	char s[4] = { 1,2,3,4 };
	//一個指針指向4個位元組的數組
	char(*p)[4] = &s;
	//cout << (*p)[0] << endl;相當于s[0]
	cout << p << endl;
	cout << &s << endl;
	//指針+1,相當于原位址+sizeof(類型)*1;
	cout << p + 1 << endl;
	//數組指針的用途,主要用于二維數組一行的輸出,可以換行;
}
           
void test07()
{
	char s[2][4] = { 1,2,3,4 };
	char(*p)[4] = &s[0];
	cout << p << endl;
	printf("%p\r\n", &s[0][0]);
	//cout <<&s[0][0] << endl;
	cout << p + 1 << endl;
	//%p輸出位址的,%p一般以十六進制整數方式輸出指針的值
	printf("%p\r\n", &s[1][0]);
	//cout << &s[1][0] << endl;
}
           

字元串與指針

C++可以用三種方法通路一個字元串,利用string時,記得加頭檔案;

是以上面的char*可以看成字元串

void test08()
{
	char str[] = "HELLO,WORLD";
	cout << str << endl;
	string str1 = "HELLO,CDD";
	cout << str1 << endl;
	char* str2 = "HELLO,MWJ";
	cout << str2 << endl;
}
           

繼續閱讀