If the following assignment is valid:
int a[2] = {1,2};
int* b = a;
then what is wrong with this:
int a[2][2]={1,2,3,4};
int** b = a;
C++ gives an error that it can’t convert int[][] to int**. What is difference between the two types if int[] is the same as int*?
Take it easy. It is only a compiler error. Arrays are pretty tricky. Here is the rule:
Your first snippet looks like:
So according to the rule if
ais in the right hand side of a assignment then it decays to address of the element zero and that is why it has typeint *. This brings you toIn the second snippet what you really have is an array of arrays. (By the way, to make it explicit I’ve changed your code a bit.)
This time
awill decay to the pointer to an array of two integers! So if you would want to assignato something, you would need this something to have the same type.(This syntax maybe a bit stunning to you, but just think for a moment that we have written
int *b[2];Got the point?bwould be an array of pointers to integers! Not really what we wanted…)You could stop reading here, but you could also move on, because I have not told you all the truth. The rule I mentioned has three exceptions…
The value of the array will not decay to the address of the element zero if
sizeof&Let’s explain these exceptions in more detail and with examples:
And finally
Here not a pointer to “Hello world” is copied, but the whole string is copied and a points to this copy.
There is really a lot of information and it is really difficult to understand everything at once, so take your time. I recommend you to read K&R on this topic and afterwards this excellent book.