Home  >  Article  >  Backend Development  >  What is the difference between pointer array and array pointer

What is the difference between pointer array and array pointer

青灯夜游
青灯夜游Original
2023-01-06 16:50:069778browse

区别:对指针数组来说,首先它是一个数组,数组的元素都是指针,也就是说该数组存储的是指针,数组占多少个字节由数组本身决定;而对数组指针来说,首先它是一个指针,它指向一个数组,也就是说它是指向数组的指针,在 32 位系统下永远占 4 字节,至于它指向的数组占多少字节,这个不能够确定,要看具体情况。

What is the difference between pointer array and array pointer

本教程操作环境:windows7系统、c99版本、Dell G3电脑。

一、数组指针和指针数组的定义

1.指针数组:定义 int *p[n];

指针数组可以说成是”指针的数组”,由于*p没有括号,首先这个变量是一个数组,其次,”指针p”修饰这个数组,意思是说这个数组的所有元素都是指针类型,而指针所占的字节数和其类型无关,只与系统有关,在32位系统下,任何类型的指针占据4个字节,在64位系统下,任何类型的指针占据8个字节。

2.数组指针:定义 int (*p)[n];

由于()的优先级高,首先说明p是一个int类型指针,它是指向一个整型(int)的一维数组,这个一维数组的长度是n,也可以说是总共有n个格子。数组指针也称指向一维数组的指针,亦称行指针。

数组指针也可以称为“数组的指针”,首先这个变量是一个指针,其次,”数组”修饰这个指针,意思是说这个指针存放着一个数组的首地址,或者说这个指针指向一个数组的首地址。

What is the difference between pointer array and array pointer

二、数组指针和指针数组的使用

1.数组指针

首先定义一个数组指针,既然是数组的指针,说明是用指针p去指向一个一维数组,即:

int (*p)[[4]];
 //这里定义int类型,p是一个指针,指向一维数组的首地址,这个一维数组大小为4

也就是说,int类型的指针p指向int [[4]]的数组,而数组的每一个元素是一个int类型的变量。

数组指针本质是一个指针,而指针的作用就是用来指向变量的地址,所以数组指针一般可以这样使用(示例):

void fun(int (*P)[4]); //子函数中的形参,数组指针 

a[3][4] = {0}; //主函数中定义的二维数组
fun(a); //主函数调用子函数的实参,是二维数组的首元素首地址

2.指针数组

对于指针数组,也就是“指针的数组”,说明这个数组的所有元素都是指针类型。不妨定义指针p,例如:

int *p[[4]];
 //这里数组长度为4,所有元素均为int类型的指针

代码如下(示例):

void Fun(char** str);    //子函数中的形参,指针数组

int main()
{
	int arr[3][4];
	char* str = "abc";
	char** q = &str;
}

指针数组和数组指针参数传递问题

传递的参数 匹配需要的形参
int *p[4] int **p(指针数组或者二级指针)
int (*p)[4] int (*p)[4](不变)
int [3][4] int (*p)[4](数组指针)
int **p int **p(不变)

三、实际使用的例子

例子:使用指针数组打印出:“sun wu kong”

What is the difference between pointer array and array pointer

// 代码块  打印“sun wu kong”
char str1[] = { 's', 'u', 'n' , '\0' };
char str2[] = { 'w', 'u' ,'\0' };
char str3[] = { 'k', 'o', 'n', 'g' ,'\0' };
char* p[3] = { str1, str2, str3 };

总结

提示:这里对文章进行总结:

1、数组指针简单理解为“数组的指针”,首先这个变量是一个指针,其次,”数组”修饰这个指针,意思是说这个指针存放着一个数组的首地址,或者说这个指针指向一个数组的首地址。

2、指针数组简单理解为“指针的数组”,首先这个变量是一个数组,其次,”指针p”修饰这个数组,意思是说这个数组的所有元素都是指针类型。

3、关于函数传参的问题:传递的参数:int *p[4] -> 匹配需要的形参:int **p(指针数组或者二级指针);传递的参数:int (*p)[4] -> 匹配需要的形参:int (*p)[4](不变)。

【相关推荐:C语言视频教程编程教学

The above is the detailed content of What is the difference between pointer array and array pointer. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn