为什么在将指针分配给2D数组时需要指定行? [英] Why does one need to specify the row while assigning a pointer to a 2D Array?
问题描述
当未提及2D数组的行时,编译器会指出来自不兼容指针类型的赋值",我一直认为没有括号的数组表示第一个元素的地址,在这种情况下,元素twodstring [0]的地址[0]
The compiler states "assignment from incompatible pointer type" when the row of the 2D array is not mentioned, I always thought an array without brackets means the address of the first element, in this case address of the element twodstring[0][0]
在提到该行时,编译器未声明错误,我想知道为什么会这样吗?
Compiler does not state an error when the row is mentioned, I was wondering why is this the case?
#include<stdio.h>
int main()
{
char onedstring[]={"1D Array"};
char twodstring[][5]={"2D","Array"};
char *p1,*p2;
p1=onedstring;
p2=twodstring;
p2=twodstring[1];
}
推荐答案
二维数组
char a[M][N];
可以使用typedef通过以下方式声明
can be declared using a typedef the following way
typedef char T[N];
T a[M];
因此可以像这样声明指向数组a
的第一个元素的指针
So a pointer to the first element of the array a
can be declared like
T *p = a;
其中,T
是类型char[N]
的别名.现在进行反向替换,我们可以写
where T
is an alias for the type char[N]
. Now making the reverse substitution we can write
char ( *p )[N] = a;
也就是说,二维数组的元素是一维数组.
That is elements of a two-dimensional array are one-dimensional arrays.
此声明
char ( *p )[N] = a;
等同于
char ( *p )[N] = &a[0];
其中a[0]
具有类型char[N]
.因此,指针指向数组的第一个行".
where a[0]
has the type char[N]
. So the pointer points to the first "row" of the array.
取消引用指针,您将获得类型为char[N]
的对象.
Dereferencing the pointer you will get an object of the type char[N]
.
请注意,可以像这样声明二维数组
Pay attention to that a two-dimensional array can be declared like
char ( a[M] )[N];
因此,将一维数组声明符a[M]
替换为指针,您将得到
So substituting the one-dimensional array declarator a[M]
for pointer you will get
char ( a[M] )[N];
char ( *p )[N] = a;
如果您要声明这样的指针
If you will declare a pointer like this
char *p1;
那么你可以写个例子
p1 = a[1];
该表达式中的
a[1]
是类型为char[N]
的一维数组.使用该表达式作为初始化程序,该数组将转换为指向其第一个类型为char *
的元素的指针.
in this expression a[1]
is a one-dimensional array of the type char[N]
. Using the expression as an initializer the array is converted to pointer to its first element that has the type char *
.
所以这个表达式语句
p1 = a[1];
等同于
p1 = &a[1][0];
取消引用此指针,您将获得类型为char
的对象.
Dereferencing this pointer you will get an object of the type char
.
这篇关于为什么在将指针分配给2D数组时需要指定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!