C language basics: pointer arrays and array pointers

        An array of pointers

        In this section, we will learn about an array, which is special and common. It is special because this array is an array of pointers, that is to say, we have an array, and the variable type stored in this array is a pointer variable; it is said to be ordinary because array variables are actually no different from other ordinary variables. Pointer variables It is a variable that can store memory addresses, so they can also be defined as a series of continuous variable collections. This collection is an array of pointers. For example, we can define a set of variables, which is an array of 4 elements, each of which is a pointer to an int variable:

int a = 0;
int b = 1;
int c = 2;
int d = 3;

int *p[4];

p[0] = &a;
p[1] = &b;
p[2] = &c;
p[3] = &d;

printf("%d\n", *p[0]);
printf("%d\n", *p[1]);
printf("%d\n", *p[2]);
printf("%d\n", *p[3]);

        Here we should pay attention to the priority of the operator. Since the priority of * is lower than that of [], in the whole expression, p must be combined with [4] to represent an array, and then combined with * to represent The type of each array element is a pointer variable. Let's take a look at multidimensional arrays and multidimensional pointer arrays again:

int array[2][3] =
{
	{ 0, 1, 2 },
	{ 3, 4, 5 }
};
int *p[2][3];
for (int i = 0; i < 2; i++)
{
	for (int j = 0; j < 3; j++)
	{
		p[i][j] = &array[i][j];
	}
}
for (int i = 0; i < 2; i++)
{
	for (int j = 0; j < 3; j++)
	{
		printf("%d ", *p[i][j]);
	}
	printf("\n");
}

        值得注意的地上是多维数组表示的是整型多维数组表示的是很数组中每一个元素的类型都 是型型的变量,而多维指针数组中表示的是数组中每一个元素的类型都是指针型变量。而在循环赋值时我们将数组指针数组中的每一个指针都指向了整型数组中的每一个元素。

二、指针数组与数组指针

        接下来我们来看一看一个非常容易混淆的两个概念:“指针数组”与“数组指针”。

指针数组:表示的是一个数组,数组中每一个变量都是指针型变量;

数组指针:表示的是一个指针类型的变量,这个指针变量指向的是一个数组。

        我们用一个例子来仔细对它们的区别做说明:

int array[2][3] =
{
	{ 0, 1, 2 },
	{ 3, 4, 5 } 
};

//指针数组
int *p[2][3];
for (int i = 0; i < 2; i++)
{
	for (int j = 0; j < 3; j++)
	{
		p[i][j] = &array[i][j];
	}
}

for (int i = 0; i < 2; i++)
{
	for (int j = 0; j < 3; j++)
	{
		printf("%d ", *p[i][j]);
	}
	printf("\n");
}

//数组指针
int (*q)[3] = array;
for (int i = 0; i < 2; i++)
{
	for (int j = 0; j < 3; j++)
	{
		printf("%d ", q[i][j]);
	}
	printf("\n");
}

        对于上面程序中两种不同的指针数组和数组指针请大家一定要分清。int *p[2][3];所表示的是一个二维数组,数组的每一个元素都是一个指针变量。也就是说,这是一个具有6个指针型变量的数组;而int (*q)[3] = array;所表示的是数组指针,注意:这里只定义了一个指针型变量q,它指向一个二维数组array。而对于q来说,它告诉编译器,这是一个指针,这个指针指向一个具有3列的数组变量。

        关于这两个概念不太容易理解,请大家自己动手编写相关的程序,通过编写程序、查看其运行结果来慢慢消化这两个概念,并熟练掌握它们的原理与用法。


欢迎关注公众号:编程外星人

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325691172&siteId=291194637