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]".)
            Asked
            
        
        
            Active
            
        
            Viewed 250 times
        
    1
            
            
         
    
    
        billz
        
- 44,644
- 9
- 83
- 100
 
    
    
        user2060185
        
- 25
- 2
- 
                    2http://stackoverflow.com/a/4810676/964135 helps – Pubby Feb 11 '13 at 04:04
- 
                    See also http://stackoverflow.com/questions/2565039/how-are-multi-dimensional-arrays-formatted-in-memory - it confirms what PQuinn said, but also includes an important warning about how to access... – Floris Feb 11 '13 at 04:18
- 
                    @ Pubby & Floris Thanks that really helps me visualize it – user2060185 Feb 11 '13 at 04:34
3 Answers
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...
 
    
    
        Floris
        
- 45,857
- 6
- 70
- 122
- 
                    +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). – WhozCraig Feb 11 '13 at 04:12
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.
 
    
    
        PQuinn
        
- 992
- 6
- 11
- 
                    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. – Floris Feb 11 '13 at 04:15
- 
                    This will always be true. If there is a compiler out there that violates this, only seriously masochistic crazies should ever use it. – PQuinn Feb 11 '13 at 04:20
- 
                    @PQuinn - valid point about "masochistic crazies". But see my earlier link to a more detailed discussion about this. – Floris Feb 11 '13 at 04:28
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<
