Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addresses in 2D Matrix

I want to know what is the difference between matrix, &matrix, matrix[0] and &matrix[0]+1? nd Also its memory representation.

 int main(){
       int matrix[4][3];
       printf("%u\n",&matrix);
       printf("%u\n",&matrix+1);
       printf(" %u\n",matrix);
       printf("%u\n",matrix[0]+1);    
       printf(" %u\n",&matrix[0]);
       printf(" %u\n",&matrix[0]+1);
}

PLATFORM ---- GCC ubuntu 10.04

like image 403
Anil Arya Avatar asked Mar 17 '26 14:03

Anil Arya


1 Answers

In C, a multi dimensional array is just a contiguous memory block. In your case, a 4 x 3 array is a contiguous block of 12 elements and 'matrix' is the pointer to start address of the memory block. Here matrix, matrix[0], matrix[0][0] all refer to starting address of the memory block

The compiler converts your statements to

&matrix = get the starting address of the memory block
&matrix+1 = add '1' to matrix datatype, i.e. add 12 (total elements in matrix) * size of int (4 bytes) = 48 bytes.

matrix[0]+1 = address of first row, second element, i.e. &matrix[0][1]
&matrix[0] = address of first row, first element which is nothing but starting address of matrix
&matrix[0]+1 = add one row to starting address of matrix, i.e. 3 elements in a column * size of int(4 byte) = 12 bytes. Note that this is equivalent to (&matrix[0])+1 and not &(matrix[0]+1)
like image 165
Chethan Ravindranath Avatar answered Mar 19 '26 02:03

Chethan Ravindranath