指针的理解系列--3

五、指针变量的类型

1、字符指针变量

字符指针:char*

1.1【使用方法】
#include<stdio.h>
int main()
{
	char ch = 'w';
	char* pc = &ch;
	*pc = 'w';
	return 0;
}
1.2【const修饰】
#include<stdio.h>
int main()
{
	//*pstr里面的内容不可以被改变
	const char* pstr = "hello bit";  
	printf("%s\n", pstr);
	return 0;
}
1.3【赋值问题】
#include<stdio.h>
int main()
{
	const char* p = "abcdef";
	printf("%c\n", *p);  //a
	printf("%s\n", p);   //abcdef
	return 0;
}

这里的赋值是将字符串中的首字符的地址赋值给了p

(把一个常量字符串的首字符a的地址存放到指针变量p里面)

1.4【例题】
#include<stdio.h>
int main()
{
	char str1[] = "hello bit";
	char str2[] = "hello bit";
	const char* str3 = "hello bit";
	const char* str4 = "hello bit";

	if (str1 == str2)  //这里比较的是这两个数组首元素地址是否相等
		printf("str1 and str2 are same\n");
	else
		printf("str1 and str2 are not same\n");   //not same

	if (str3 == str4)   //这里比较str3、str4里面放的值
		printf("str3 and str4 are same\n");      //same
	else
		printf("str3 and str4 are not same\n");

	return 0;
}

str3 和 str4指向的是同一个字符串常量,C/C++会把常量字符串储存到一个内存区域。

(内容相同的常量字符串只需要保存一份即可)

但是用相同的常量字符串去初始化不同的数组会开辟出不同的内存块。

所以str1、str2不同;str3、str4相同。

2、数组指针变量

2.1【定义】

数组指针变量是指针变量;存放的是数组的地址,能够指向数组的指针变量

int (*p)[10]

2.2【区分】

2.3【元素解析】

p就是数组指针,存放的是数组的地址

2.4【二维数组传参】

将一个二维数组传参给一个函数----

Plan A


#include<stdio.h>
void test(int a[3][5], int r, int c)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < r; i++)
	{
		for (j = 0; j < c; j++)
		{
			printf("%d ", a[i][j]);
		}
		printf("\n");
	}
}
int main()
{
	int arr[3][5] = { {1,2,3,4,5},{2,3,4,5,6},{3,4,5,6,7} };
	test(arr, 3, 5);  //这里arr传的是第一行{1,2,3,4,5}的地址
	return 0;
}

Plan B

#include<stdio.h>
void test(int(*p)[5],int r,int c)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < r; i++)
	{
		for (j = 0; j < c; j++)
		{
			printf("%d ", *(*(p+i)+j));
			             //(*(arr+i))[j]
			//*(arr+i) == arr[i]
			//arr[i]是第i行的数组名,数组名又表示首元素的地址
			//arr[i]表示的是arr[i][0]的地址
		}
		printf("\n");
	}
}
int main()
{
	int arr[3][5] = { {1,2,3,4,5},{2,3,4,5,6},{3,4,5,6,7} };
	test(arr, 3, 5);  //这里arr传的是第一行{1,2,3,4,5}的地址
	return 0;
}

2.5【二维数组传参本质】

【1】、

二维数组的数组名 表示的是 第一行的地址,

二维数组传参本质上是传递了地址,传递的是第一行这个一维数组的地址

【2】、

二维数组传参,形参的部分可以写成数组,也可以写成指针形式。

到这里指针理解系列3就结束啦!(未完待续哦)

猜你喜欢

转载自blog.csdn.net/2301_78136992/article/details/139720851