From my understanding of two-dimensional arrays, let's say if I declare
int a[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};, it will be stored in a memory in exact order.
And the address of each row can be written like this:
a[0] is equal to &a[0][0], a[1] is equal to &a[1][0], and a[2] is equal to &a[2][0]. So each a[n] is a int* type variable.
And since array name a is originally &a[0], it will be a int** type variable.
From this knowledge, I assumed that writing code like this will occur error when assigning a to p, since the type is different.
#include <stdio.h>
int main() {
int a[3][3] = { 72, 4, 5,
6, 7, 8,
9, 10, 11 };
int* p;
p = a; //possible error, from int** to int*
printf("*p : %d\n", *p);
return 0;
}
But somehow the result shows the value of a[0][0], which is 72. What happened here? Am I understanding something wrong about two-dimensional matrix?
You are wrong. Arrays used in expressions with rare exceptions are indeed converted to pointers to their first elements. But in this case the type of elements of the array is
int[3]. So the arrayaused in expressions is converted to a pointer of the typeint ( * )[3].As for this code snippet
then values of addresses of the expressions
a,a[0]and&a[0][0](it is the value of the address of the extent of memory occupied by the array) are equal each other. So using the value and interpreting it as a value of the type&a[0][0]you will get the value of the first elementa[0][0].