Dreferencing 2 d array

Take a look at this piece of code: -

#include<stdio.h> int main() { int arr[2][2]={1,2,3,4}; printf("%d %u %u",**arr,*arr,arr); return 0; } 

When I compiled and executed this program, I got the same value for arr and * arr, which is the starting address of the 2 d array. For example: - 1 3214506 3214506

My question is: why does dereferencing arr (* arr) not print the value stored at the address contained in arr?

+2
source share
2 answers

* arr is an array of integers of length 2, so it has the same address as arr. Both of them point to the beginning of their arrays, which is the same place.

+5
source

in C, a 2d array is not represented in memory as an array of arrays; rather, it is a regular 1st array in which the first measurement given is necessary to calculate the correct offset within the array at runtime. That's why in a multidimensional array you always need to specify all sizes except the last (which is not required); for example, if you declare an array like

 int a[2][3][4]; 

the array will be represented in memory as a single array of 2 * 3 * 4 elements. An attempt to access an element in position (i, j, k) will actually be translated to access an element 3 * i + 4 * j + k in a simple array. In a sense, the initial sizes are needed to know where to put the "line breaks" in a 1d array.

0
source

Source: https://habr.com/ru/post/1435484/


All Articles