Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointers and multi-dimensional arrays [duplicate]

Tags:

c++

Possible Duplicate:
How do I use arrays in C++?
Is 2d array a double pointer?
Two dimensional arrays and pointers

I know that this is a very basic question but no amount of googling cleared this for me. That's why am posting it here. In c++ consider the declaration int x[10];

This is a 1-dimensional array with x being the base pointer that is it contains the address of the first element of the array. So x gives me that address and *x gives the first element.

similarly for the declaration

 int x[10][20];

what kind of variable is x here. When i do

 int **z = x;

the compiler says it cannot convert int (*)[20] to int **.And why does cout<<x; and cout<<*x; give the same value?? And also if i declare an array of pointers as

 int *p[10];

then is there a difference between x and p ( in their types) ?? because when one declares int x[10] and int *p then it is valid to assign x to p but it is not so in case of two dimensional arrays? why? Could someone please clear this for me or else provide a good resource material on this.

like image 326
newbie Avatar asked Aug 10 '26 19:08

newbie


1 Answers

Arrays and pointers aren't the same thing. In C and C++, multidimensional arrays are just "arrays of arrays", no pointers involved.

int x[10][20];

Is an array of 10 arrays of 20 elements each. If you use x in a context where it will decay into a pointer to its first element, then you end up with a pointer to one of those 20-element arrays - that's your int (*)[20]. Note that such a thing is not a pointer-to-a-pointer, so the conversion is impossible.

int *p[10];

is an array of 10 pointers, so yes it's different from x.

In particular, you may be having trouble because you seem to think arrays and pointers are the same thing - your question says:

This is a 1-dimensional array with x being the base pointer that is it contains the address of the first element of the array. So x gives me that address and *x gives the first element.

Which isn't true. The 1-dimensional x is an array, it's just that in some contexts an array decays into a pointer to its first element.

Read the FAQ for everything you want to know about this subject.

like image 123
Carl Norum Avatar answered Aug 12 '26 11:08

Carl Norum



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!