1

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]".)

3
  • 2
    stackoverflow.com/a/4810676/964135 helps Commented 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... Commented Feb 11, 2013 at 4:18
  • @ Pubby & Floris Thanks that really helps me visualize it Commented Feb 11, 2013 at 4:34

3 Answers 3

2

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...

Sign up to request clarification or add additional context in comments.

1 Comment

+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).
1

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

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.
This will always be true. If there is a compiler out there that violates this, only seriously masochistic crazies should ever use it.
@PQuinn - valid point about "masochistic crazies". But see my earlier link to a more detailed discussion about this.
0

In static arrays, the memory allocation is contiguous. It can be elaborated via the following example int arr[2][5]= { {1,2,3,4,5}, {6,7,8,9,10}}; cout<

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.