Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two dimensional array address and corresponding pointer to its 1st element

Tags:

arrays

c

pointers

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[ ][ ].

Why does this happen? Do I comprehend the pointer and array concept wrong?

like image 891
ButterLover Avatar asked Dec 13 '25 23:12

ButterLover


2 Answers

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. So this code would work:

char (*pa_data)[5] = data;

Here pa_data is a pointer to array. 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. 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. (In particular, you could not say something like pp_data = &data[0][0].)

See also this question in the C FAQ list.

like image 70
Steve Summit Avatar answered Dec 15 '25 11:12

Steve Summit


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[0] is an array of char. Therefore the type of data will become pointer to an array of 5 char, i.e. char (*)[5].

char ** and char (*)[5] are of different type, i.e. incompatible type.

like image 32
haccks Avatar answered Dec 15 '25 11:12

haccks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!