I believe a better example is:
Originally Posted by rakeshkool27
which is like a pointer to 1D array. What you have to keep in mind is that you can "trade" a pointer for one dimension.
ptr = a;
This is NOT valid, you cannot trade two pointers for 2D dimensions:
But you can do this
ptr = a; //compile error
provided that ptr points at a valid memory location.
ptr = 0;
This might seems confusing. But you just have to remember the "trade one dimension for one pointer" thing.
More in depth:
The reason you are not allowed to do the 2nd code is that an multi-dimensional array in C is not like a pointer. Here is the difference of a 2D array and a pointer to a pointer. Consider this:
for the first, the compiler will do this
ptr = 0; //ptr is int**
a = 0; //a is a
1) Read the value of ptr. Add the first index. Thus ptr+1
2) Read where ptr+1 points. Thus read *(ptr+1)
3) Add the second index to that. Thus *(ptr+1)+1
4) Assign the value 0 where that points to. Thus do *(*(ptr+1)+1) = 0
What is the difference in the second case. The compiler knows the size. Thus, it can optimize the process. It will simply do this:
0) Assume that MAX_X = 10 and MAX_Y =10. And you have a[x][y]. Thus here, x=1, y=1
1) Read the value of a. Add MAX_Y*x + y, thus a+10*1+1, thus a+11
2) Assign the value 0 where that points to. Thus do *(a+11) = 0
In other words, [x][y][z] = [MAX_X*MAX_Y*x + MAX_Y*y + z]
Note now why the compiler doesn't need to know all dimensions. Just all but one. Because declaring this
is valid, because teh compiler will figure out that you have tottally 6 elements. Thus you actually have x.
What is the difference with
The difference is that you give the compiler an info. That MAX_X = 10. Notice that MAX_Y is not needed. The formula is [x][y] = [MAX_X * x + y]. So the compiler thas all necessary information to translate indexes. Put if you do
the compiler wouldn't know about MAX_X. Thus you are not allowed to do so.
So when you have this:
[x][y] it can actually mean two things
1) *(array + MAX_X * x + y) if it is after an array
2) *(*(pointer+x)+y) if it is after a pointer
the bad thing is that in some books the first is not clarified
More in debth:
I mentioned "optimize". The bad thing with a pointer to a pointer is that you have an array of pointers (one piece of memory) and each pointer in the array points to another array. If you have ptr, you have an array of 10 pointers and each pointer points to an array of 10 integers. Now, if you have a you have a big array with 100 integers. A contiguous space, which is always more beneficial. You will have more chances for a cache hit, for example.