Create a pointer to two-dimensional array

后端 未结 10 1450
温柔的废话
温柔的废话 2020-11-22 07:16

I need a pointer to a static 2-dimensional array. How is this done?

static uint8_t l_matrix[10][20];

void test(){
   uint8_t **matrix_ptr = l_matrix; //wron         


        
10条回答
  •  眼角桃花
    2020-11-22 07:42

    G'day,

    The declaration

    static uint8_t l_matrix[10][20];
    

    has set aside storage for 10 rows of 20 unit8_t locations, i.e. 200 uint8_t sized locations, with each element being found by calculating 20 x row + column.

    So doesn't

    uint8_t (*matrix_ptr)[20] = l_matrix;
    

    give you what you need and point to the column zero element of the first row of the array?

    Edit: Thinking about this a bit further, isn't an array name, by definition, a pointer? That is, the name of an array is a synonym for the location of the first element, i.e. l_matrix[0][0]?

    Edit2: As mentioned by others, the comment space is a bit too small for further discussion. Anyway:

    typedef uint8_t array_of_20_uint8_t[20];
    array_of_20_uint8_t *matrix_ptr = l_matrix;
    

    does not provide any allocation of storage for the array in question.

    As mentioned above, and as defined by the standard, the statement:

    static uint8_t l_matrix[10][20];
    

    has set aside 200 sequential locations of type uint8_t.

    Referring to l_matrix using statements of the form:

    (*l_matrix + (20 * rowno) + colno)
    

    will give you the contents of the colno'th element found in row rowno.

    All pointer manipulations automatically take into account the size of the object pointed to. - K&R Section 5.4, p.103

    This is also the case if any padding or byte alignment shifting is involved in the storage of the object at hand. The compiler will automatically adjust for these. By definition of the C ANSI standard.

    HTH

    cheers,

提交回复
热议问题