Reputation: 97
i just got this task of finding 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'm courious about is the *(pointerArray[i] + j), I think it's the same thing as pointerArray[i][j], since you can access the element both ways, But can anyone tell me what is actually happening with the *()? Like how does the compiler know that im asking for the same as pointerArray[i][j]?
Thanks for the answers!
Upvotes: 4
Views: 103
Reputation: 528
In this context, the *
operator is the dereference operator. The value it prepends will be the location in memory at which it will return a value.
The parenthesis are grouping an addition operation so that the compiler knows that the result of this addition will be used for the dereference. It's simply 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 imagine a two-dimensional array as a 2D grid of values with rows and columns, in memory the data is laid out such that each row is strung one after the next in sequential order. The first index in the array (i
) along with the type of the array (int
) tells the compiler at what offset to look for the first location in the row. The second index in the array (j
) tells it at what offset within that row to look.
*(pointerArray[i] + j)
basically means: "Find the beginning of the i
th row of data in pointerArray
, and then pick the j
th element of that row, and give me that value.
Upvotes: 2
Reputation: 258588
When you do pointerArray[i] + j
, you request the element pointerArray[i]
, which is a int*
, and increment that pointer by j
(also returning an int*
). The *(...)
simply dereferences the pointer and returns the int
at that position. *
is called the dereference operator (in this case). So yes, it's equivalent to pointerArray[i][j]
.
Upvotes: 3