Monday, 13 June 2016

c++ - pointers and multi-dimensional arrays










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



Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...