Two-dimensional array, what does * (pointerArray [i] + j) do?

I had this task to find out how this code works.

int array[rows][coloums]; int *pointerArray[rows]; for (int i = 0; i < rows; i++) { pointerArray[i] = array[i]; for (int j = 0; j < coloums; j++) { *(pointerArray[i] + j) = 0; } } 

The thing I care about is * (pointerArray [i] + j), I think this is the same as pointerArray [i] [j], since you can access the element in both directions, but can anyone tell me what is really happening with * ()? For example, how does the compiler know that im is requesting the same as an Array [i] [j] pointer?

Thanks for answers!

+4
source share
2 answers

In this context, the * operator is the dereference operator. The intended value will be the place in memory to which it will return the value.

The addition operation is grouped in parentheses so that the compiler knows that the result of this addition will be used for dereference. This is just a case of order of operations.

Keep in mind that the [] operator does the same thing as the dereference operator, because arrays are essentially a kind of pointer variable. If you represent a two-dimensional array in the form of a 2D grid of values ​​with rows and columns, the data is laid out in memory so that each row is strung one after another in sequential order. The first index in the array ( i ) along with the type of the array ( int ) tells the compiler what offset the first place in the string is looking for. The second index in the array ( j ) indicates what the offset in this row looks like.

*(pointerArray[i] + j) basically means: "Find the beginning of the ith data row in pointerArray , and then select the j element of this row and give me that value.

+2
source

When you execute pointerArray[i] + j , you request the pointerArray[i] element, which is int* , and increment that pointer by j (also returning int* ). *(...) just plays the pointer and returns int at that position. * called the dereferencing operator (in this case). So yes, this is equivalent to pointerArray[i][j] .

+3
source

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


All Articles