Im having a little trouble understanding pointers.If I declare a multi-dimensional array char ma[10][30]. What is the address of the element "ma[2][20]"? if the address must be assigned to the pointer variable, that's not "p = &ma[2][20]".)
-
2stackoverflow.com/a/4810676/964135 helpsPubby– Pubby2013-02-11 04:04:42 +00:00Commented Feb 11, 2013 at 4:04
-
See also stackoverflow.com/questions/2565039/… - it confirms what PQuinn said, but also includes an important warning about how to access...Floris– Floris2013-02-11 04:18:14 +00:00Commented Feb 11, 2013 at 4:18
-
@ Pubby & Floris Thanks that really helps me visualize ituser2060185– user20601852013-02-11 04:34:08 +00:00Commented Feb 11, 2013 at 4:34
Add a comment
|
3 Answers
The address of ma[2][20] is ma[2] + 20
since ma is a character array
or p = &(ma[2][20]) - pretty sure the brackets matter...
1 Comment
WhozCraig
+1 The parens do not matter in the second parse:
&ma[2][10] will work equally well (apart from the OP specifically requesting a different answer than that, which you also supplied).A multidimensional array is really just a contiguous chunk of memory. In this case the array is a chunk of chars (bytes) 10*30 = 300 bytes in size. The compiler is handling the accessing of this array via the two 'dimensions'.
The address of ma[2][20] is the address of 'ma' + 2*30 + 20 or 'ma+80' bytes. 'ma' is the address of the start of the chunk of memory representing the array.
3 Comments
Floris
Not sure that is always true. The compiler can allocate chunks of memory that are pointed to by ma[n] and that are not contiguous. In other words, I don't think compilers guarantee that ma[n][29] is right before ma[n+1][0], although in practice that is often the case.
PQuinn
This will always be true. If there is a compiler out there that violates this, only seriously masochistic crazies should ever use it.
Floris
@PQuinn - valid point about "masochistic crazies". But see my earlier link to a more detailed discussion about this.