Originally Posted by
rakeshkool27
So it is found the assignment of a multidimensional array to a pointer is completely different from a1D array,is it right????anyone can comment on it please.....
I believe a better example is:
Code:
int (*ptr)[10];
int a[10][10];
ptr = a;
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.
This is NOT valid, you cannot trade two pointers for 2D dimensions:
Code:
int **ptr;
int a[10][10];
ptr = a; //compile error
But you can do this
Code:
int **ptr;
...
ptr[0][1] = 0;
provided that ptr[0][1] points at a valid memory location.
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:
Code:
ptr[1][1] = 0; //ptr is int**
a[1][1] = 0; //a is a[10][10]
for the first, the compiler will do this
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
Code:
x[][2]={1,2,3,4,5,6}
is valid, because teh compiler will figure out that you have tottally 6 elements. Thus you actually have x[3][2].
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[10][10], you have an array of 10 pointers and each pointer points to an array of 10 integers. Now, if you have a[10][10] 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.