c - Create a pointer to two-dimensional array -
i need pointer static 2-dimensional array. how done?
static uint8_t l_matrix[10][20]; void test(){ uint8_t **matrix_ptr = l_matrix; //wrong idea }
i kinds of errors like:
- warning: assignment incompatible pointer type
- subscripted value neither array nor pointer
- error: invalid use of flexible array member
here wanna make pointer first element of array
uint8_t (*matrix_ptr)[20] = l_matrix;
with typedef, looks cleaner
typedef uint8_t array_of_20_uint8_t[20]; array_of_20_uint8_t *matrix_ptr = l_matrix;
then can enjoy life again :)
matrix_ptr[0][1] = ...;
beware of pointer/array world in c, confusion around this.
edit
reviewing of other answers here, because comment fields short there. multiple alternatives proposed, wasn't shown how behave. here how do
uint8_t (*matrix_ptr)[][20] = l_matrix;
if fix error , add address-of operator &
in following snippet
uint8_t (*matrix_ptr)[][20] = &l_matrix;
then 1 creates pointer incomplete array type of elements of type array of 20 uint8_t. because pointer array of arrays, have access with
(*matrix_ptr)[0][1] = ...;
and because it's pointer incomplete array, cannot shortcut
matrix_ptr[0][0][1] = ...;
because indexing requires element type's size known (indexing implies addition of integer pointer, won't work incomplete types). note works in c
, because t[]
, t[n]
compatible types. c++ not have concept of compatible types, , reject code, because t[]
, t[10]
different types.
the following alternative doesn't work @ all, because element type of array, when view one-dimensional array, not uint8_t
, uint8_t[20]
uint8_t *matrix_ptr = l_matrix; // fail
the following alternative
uint8_t (*matrix_ptr)[10][20] = &l_matrix;
you access
(*matrix_ptr)[0][1] = ...; matrix_ptr[0][0][1] = ...; // possible
it has benefit preserves outer dimension's size. can apply sizeof on it
sizeof (*matrix_ptr) == sizeof(uint8_t) * 10 * 20
there 1 other answer makes use of fact items in array contiguously stored
uint8_t *matrix_ptr = l_matrix[0];
now, formally allows access elements of first element of 2 dimensional array. is, following condition hold
matrix_ptr[0] = ...; // valid matrix_ptr[19] = ...; // valid matrix_ptr[20] = ...; // undefined behavior matrix_ptr[10*20-1] = ...; // undefined behavior
you notice works 10*20-1
, if throw on alias analysis , other aggressive optimizations, compiler make assumption may break code. having said that, i've never encountered compiler fails on (but again, i've not used technique in real code), , c faq has technique contained (with warning ub'ness), , if cannot change array type, last option save :)
Comments
Post a Comment