c - Why do we need to use double pointer to access a 2-D array? -
i trying understand multidimensional array , pointers, wrote small program understand concept:
#include<stdio.h> void show(int arr[][2]); int main() { int z[2][2] = { { 1, 2 }, {3, 4 } }; show(z); } void show(int arr[][2]) { printf("value of arr = %d", arr); printf("\n\nvalue of &arr[0]0] = %d", &arr[0][0]); } this code fragment prints same address makes sense, when edit show function:
void show(int arr[][2]) { printf("value of *arr = %d", *arr); printf("\n\nvalue of arr[0]0] = %d", arr[0][0]); } *arr still prints same address while arr[0][0] expected prints integer value , want know why need use **arr int value , if arr storing address should dereferenced *arr, isn't ?
please having hard time understanding concept.. in advance.
if @ memory layout of 2d array, things might become little bit clearer.
you have variable defined as:
int z[2][2] = {{1, 2}, {3, 4}}; memory:
z | v +-----+-----+-----+-----+ | 1 | 2 | 3 | 4 | +-----+-----+-----+-----+ another view of memory:
z[0] z[1] | | v v +-----+-----+-----+-----+ | 1 | 2 | 3 | 4 | +-----+-----+-----+-----+ another view of memory:
z[0][0] z[1][0] | z[0][1] | z[1][1] | | | | v v v v +-----+-----+-----+-----+ | 1 | 2 | 3 | 4 | +-----+-----+-----+-----+ you can see that, far pure memory location concerned,
&z == &z[0] == &z[0][0] we know when array decays pointer, value address of first element of array. hence, when used in expression decays z pointer,
z == &z[0] == &z (from above) it's puzzling z , &z evaluate same address though of different types.
type of z when decays pointer int (*)[2]. type of &z int (*)[2][2].
coming function, have:
void show(int arr[][2]) { ... } that equivalent to:
void show(int (*arr)[2]) { ... } why arr , *arr evaluate same value?
arr evaluates &z[0] main. *arr evaluates z[0] main, evaluates &z[0][0] main.
we have seen value of &z[0] , &z[0][0] same. hence arr , *arr in show() evaluate same address.
Comments
Post a Comment