Why does one need to specify the row while assigning a pointer to a 2D Array?

泄露秘密 提交于 2019-12-23 16:06:41

问题


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];

}

回答1:


A two-dimensional array

char a[M][N];

can be declared using a typedef the following way

typedef char T[N];

T a[M];

So a pointer to the first element of the array a can be declared like

T *p = a;

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.

This declaration

char ( *p )[N] = a;

is equivalent to

char ( *p )[N] = &a[0];

where a[0] has the type char[N]. So the pointer points to the first "row" of the array.

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];

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;

then you may write for example

p1 = a[1];

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 *.

So this expression statement

p1 = a[1];

is equivalent to

p1 = &a[1][0];

Dereferencing this pointer you will get an object of the type char.




回答2:


Let's look at these lines:

char twodstring[][5]={"2D","Array"};
char *p2;
p2=twodstring;

In the last line, you just write the identifier of an array. This evaluates to a pointer to the first array element. But this first array element doesn't have the type char -- it is an array itself with the type char [5].

If you want this assignment to work, you have to declare p2 with the correct type like this:

char twodstring[][5]={"2D","Array"};
char (*p2)[5];
p2=twodstring;


来源:https://stackoverflow.com/questions/47081504/why-does-one-need-to-specify-the-row-while-assigning-a-pointer-to-a-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!