天天看点

指针数组,数组指针,字符串与指针指针数组与数组指针指针数组字符串与指针

指针数组与数组指针

在研究指针数组与数组指针的时候,遇到了这个困惑,后面解答。

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;
}
           

继续阅读