[英]Two dimensional array address and corresponding pointer to its 1st element
In terms of one dimensional array, its array name is also the address of the first element. 就一维数组而言,其数组名称也是第一个元素的地址。 So it is fine to assign it to a pointer, like below:
所以可以将它分配给指针,如下所示:
char data[5];
char* p_data=data;
So I think it should be the same with two dimensional array. 所以我认为它应该与二维数组相同。 The array name should be the address of the first element's address.
数组名称应该是第一个元素地址的地址。 So, I'd like to do something like this:
所以,我想做这样的事情:
char data[5][5];
char** pp_data=data;
Then I get a warning saying the pointer type char**
is incompatible with char[ ][ ]
. 然后我收到警告说指针类型
char**
与char[ ][ ]
不兼容。
Why does this happen? 为什么会这样? Do I comprehend the pointer and array concept wrong?
我理解指针和数组概念错了吗?
You're right that an array is often referred to by a pointer to its first element. 你是对的,数组通常由指向其第一个元素的指针引用。 But when you have the "two dimensional" array
但是当你拥有“二维”阵列时
char data[5][5];
what you actually have is an array of arrays . 你实际拥有的是一个数组数组 。 The first element of the array
data
is an array of 5 characters. 数组
data
的第一个元素是一个包含5个字符的数组。 So this code would work: 所以这段代码可行:
char (*pa_data)[5] = data;
Here pa_data
is a pointer to array . 这里
pa_data
是一个指向数组的指针 。 The compiler won't complain about it, but it may or may not actually be useful to you. 编译器不会抱怨它,但它实际上可能对您有用,也可能没有用。
It's true that a pointer-to-pointer like your char **pp_data
can be made to act like a two-dimensional array, but you have to do some memory allocation for it to work. 确实,像
char **pp_data
这样的指针指针可以像二维数组一样工作,但你必须做一些内存分配才能使它工作。 It turns out that in the array-of-arrays char data[5][5]
there's no pointer-to- char
for pp_data
to be a pointer to. 事实证明,在阵列的阵列的
char data[5][5]
有没有指针TO- char
为pp_data
是一个指针。 (In particular, you could not say something like pp_data = &data[0][0]
.) (特别是,你不能说像
pp_data = &data[0][0]
。)
See also this question in the C FAQ list . 另请参阅C FAQ列表中的此问题 。
Two dimensional array is actually an array of arrays . 二维数组实际上是一个数组数组 。 It means the first element of that array is an array.
这意味着该数组的第一个元素是一个数组。 Therefore a two dimensional array will be converted to pointer to an array (its first element).
因此,二维数组将转换为指向数组(其第一个元素)的指针。
In 在
char data[5][5];
when used in expression, wit some exception, data
will be converted to pointer to its first element data[0]
. 当在表达式中使用时,有一些例外,
data
将被转换为指向其第一个元素data[0]
指针。 data[0]
is an array of char
. data[0]
是char
数组。 Therefore the type of data
will become pointer to an array of 5 char
, ie char (*)[5]
. 因此,
data
类型将成为指向5 char
数组的指针 ,即char (*)[5]
。
char **
and char (*)[5]
are of different type, ie incompatible type. char **
和char (*)[5]
属于不同类型,即不兼容类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.