Cast T [] [] to T *

Is it possible to distinguish a 2D array of type Tto T*and dereference elements?

Since the memory layout of the 2D array is linear, the base pointer must be equal to the pointer to the first element. Since the final type they point to is also the same, there should be no problems with alignment explode.

Or is there some aspect that can cause Undefined behavior?

Just to be clear, I mean something like this -

int arr[10][10];
int p = *((int*) arr);

Also, the same question, if I refer to elements outside the first array ie (int *) arr + 13. Will it fall within the scope of access outside borders? Since I am looking beyond the borders of the first array.

+4
source share
1 answer

Casting is OK. What really can be questionable is to use a pointer to an element inside one subarray to access elements in another: although the operation is clearly defined at a lower level (everything is correctly aligned, not populated, the types are the same, ...), my view about standard C was that it was formulated in such a way as to allow border validation implementations to be standards.

Note, however, that linear movement of a multidimensional array may nevertheless be acceptable, since a pointer pointing after a subarray (which usually should not be dereferenced) also turns out to be a pointer to the first element of the next subarray. This thought leads to the fact that pointer arithmetic is nonassociative:

, , (int *)arr + 13, undefined 1 , ((int *)arr + 10) + 3.

, , , .. (int *)((char *)arr + 13 * sizeof (int)), , , , .

, , - , .


1 C11, 6.5.6 Β§8

[...] , ; undefined. [...]

+4

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


All Articles