The two-dimensional address of the array and the corresponding pointer to its 1st element

In terms of a one-dimensional array, its array name is also the address of the first element. Therefore, it should be assigned to a pointer as shown below:

char data[5];
char* p_data=data;

      

So I think it should be the same with a 2D array. The array name must be the address of the first element. So, I would like to do something like this:

char data[5][5];
char** pp_data=data;

      

Then I get a warning that the pointer type is char**

not compatible with char[ ][ ]

.

Why is this happening? I don't understand the concept of pointer and array?

+3


source to share


2 answers


You are correct that an array is often referenced by a pointer to its first element. But when you have a "two-dimensional" array

char data[5][5];

      

what you actually have an array of arrays. The first element of the array data

is a 5 character array. So this code will work:

char (*pa_data)[5] = data;

      



Here pa_data

is a pointer to an array. The compiler won't complain about this, but it may or may not be helpful to you.

It is true that a pointer to a pointer like yours char **pp_data

can be implemented as a 2 dimensional array, but you need to do some memory allocation for it to work. It turns out that there is no pointer to << 26> in the array of arrays char data[5][5]

for the pointer pp_data

. (In particular, you might not say something like pp_data = &data[0][0]

.)

See also this question in the C FAQ .

+5


source


A two-dimensional array is actually an array of arrays. This means that the first element of this array is an array. Therefore, the two-dimensional array will be converted to a pointer to the array (its first element).

IN

char data[5][5];  

      



when used in an expression, with some exception, data

will be converted to a pointer to its first element data[0]

. data[0]

is an array char

. Therefore, the type data

will become a pointer to an array of 5 char

, i.e. char (*)[5]

...

char **

and char (*)[5]

are of a different type, that is, an incompatible type.

+2


source







All Articles