c/c++ : 2-D array variable subscript -


this question has answer here:

int a[3][3]={5}; printf("&a = %u \n = %u \n*a = %u\n&a[0][0]=%d\na[0][0]", &a, a, *a, &a[0][0], a[0][0]); 

output:-

&a = 2359028  = 2359028 *a = 2359028 &a[0][0]=2359028 a[0][0] =5 

how can these same? if value of a=2359028, shouldn't *a give value @ address 2359028 i.e. 5?

  1. &a gives address of array. it's of type int (*)[3][3]. easy.

  2. a denotes array , undergo array-to-pointer conversion become pointer array's first element. array's first element subarray of type int[3], pointer subarray. pointer of type int (*)[3]. has same address before because first subarray @ start of array.

  3. with *a, array undergoes array-to-pointer conversion again same pointer subarray before. dereference subarray itself. expression denotes subarray undergoes array-to-pointer conversion, giving pointer its first element. first element of type int, pointer of type int*. address of first element same address of subarray part of, which, we've seen, same address entire array.

  4. &a[0][0] first gets first element of first subarray, takes address of it. gives same pointer in previous point.

therefore, of these pointers have same value.

diagrammatically:

  0,0   0,1   0,2   1,0   1,1   1,2   2,0   2,1   2,2 ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ │ int │ int │ int │ int │ int │ int │ int │ int │ int │ └─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘  └─────────────────────────────────────────────────────┘             &a points @ entire array  └─────────────────┘   gives pointer first subarray  └─────┘   *a gives pointer element 0,0   , &a[0][0] 

these regions begin @ same address, pointers have same value.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -