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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With