Reputation: 209
A couple questions about 2D arrays in C.
If I create an two dimensional array:
int c[5][25];
Then create a pointer to the beginning of the array:
int *p = c;
Edit: Changing the second line to:
int (*p)[25] = c;
worked. Will this still let me access the array in the following questions?
Would *(c+26)
access the array at c[1][1]
?
I know in a one dimensional array like the following:
double *p;
double balance[10];
p = balance;
*(balance + 4)
is the same as balance[4]
, but wasn't sure if the memory is assigned "back to back" for a 2D array.
Can you access c[1][1]
by doing something like c[2][-24]
?
Would be an odd way to do it, but I couldn't find anything addressing that specific scenario.
Would you be able to access c[1][1]
by the statement p[1][1]
?
My guess would be no, since p is a pointer array.
Saw these examples a while ago and wrote them down, but don't remember if they are correct or not:
1[c[1]];
26[p];
Would either of those be equivalent to c[1][1]
?
I know a lot of this is very basic, but I'm having trouble finding sources that address these specific instances online.
Thanks!
Upvotes: 3
Views: 394
Reputation: 206717
Q: 1.) Did I declare the second line correctly?
A: No, you did not. The correct way would be:
int (*p)[25] = c;
Q: 2.) Would *(c+26)
access the array at c[1][1]
?
A: No. *(c+26)
is same as c[26]
. In your case, it will lead to undefined behavior since the array index, 26
is not valid for your array.
Q: 3.) Can you access c[1][1]
by doing something like c[2][-24]
?
A: No, you cannot. Use of array indices that are out of bounds will lead to undefined behavior.
EDIT
Even though -24
appears to be an out of bound array index, using c[2][-24]
appears to be same as using c[1][1]
. I retract my first answer.
Q: 4.) Would you be able to access c[1][1]
by the statement p[1][1]
?
A: Yes, you can if you change the declaration of p
to the way I have done it.
Q: 1[c[1]];
and 26[p];
Would either of those be equivalent to c[1][1]?
A 1[c[1]]
is equivalent to c[1][1]
. 26[p]
is equivalent to p[26]
but it is not equivalent to c[1][1]
regardless of whether p
is defined your way or my way.
Upvotes: 2