2d arrays memory map in C -


i've been doing various problems on 2d array in c.each problem hitting coconut on head,as every problem uses different approach.for instance use "take 2d array(like a[2][4]),now creates 2 arrays,one of arrays of size 2, containing address of each row of 2d array(like having 2 rows,each of 4 values)".while other approaches treat contiguous 1d array representation.now approach use. proper memory map great help.below sample problem workout.

int main() {     unsigned int x[4][3] = {{1, 2, 3}, {4, 5, 6},                             {7, 8, 9}, {10, 11, 12}};    printf("%u, %u, %u", x+3, *(x+3), *(x+2)+3); }  output:2036,2036,2036 

now ,if first approach ,how come address of x+3 , *(x+3) same?

built-in arrays in c language always use "second" approach (per numbering), no exceptions. every time declare 1d, 2d, 3d or whatever-d array, in sample code, array laid out in memory contiguous memory block - 1d array of "combined" size (i.e. sizes multipled).

the "first" approach can used in "manually" assembled arrays (so called "jagged" or "ragged" arrays). language not use approach representing explcitly declared multi-dimensional arrays.

however, undefined behavior use %u format specifier print pointer values. stop doing this. function printf provides %p format printing pointers.

in x + 3 expression, object x of type unsigned [4][3] implicitly decays value of type unsigned (*)[3] - pointer points x[0] subarray. per rules of pointer arithmetic, x + 3 value of unsigned (*)[3] type points x[3] subarray.

the same thing happens in *(x + 3) expression, except x + 3 (which, again, points x[3] subarray) gets dereferenced * operator , becomes x[3] subarray itself. in context of print argument, subarray decays value of unsigned * type points x[3][0].

so, though results of x + 3 , *(x + 3) have different types, still point same location in memory. why pointer values same numerically.

the same thng happen in following simple example

int main() {   int a[10];   printf("%p %p\n", (void *) &a, (void *) &a[0]); } 

the output show same numerical value of both pointers. example bit more convoluted, same in essence.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -