Search code examples
cpointersmultidimensional-arrayimplicit-conversionvoid-pointers

Casting a pointer to Matrix on a Variable Initialization is a Reference or a Copy


I was wondering if, in the code below, matrix is just a reference to the data on pointer or is it a copy of that data. It seems to me that it is a reference, but I just want to make sure that I am right.

void foo(void *pointer) {

    uint8_t (*matrix)[5][5][5][5] = (uint8_t(*)[5][5][5][5])pointer;
}

Solution

  • The code is invalid. You may not initialize an array with a pointer. It seems there is a typo and the function should look like

    void foo(void *pointer) {
        uint8_t ( *matrix )[5][5][5][5] = (uint8_t(*)[5][5][5][5])pointer;
        // some other code
    }
    

    That is the pointer of the type void * is interpreted like a pointer to an array of the type uint8_t[5][5][5][5].

    In fact in C you may just write

    void foo(void *pointer) {
        uint8_t ( *matrix )[5][5][5][5] = pointer;
        // some other code
    }
    

    Here is a demonstrative program (that does nothing useful) that shows using such a construction.

    #include <stdio.h>
    #include <stdint.h>
    #include <string.h>
    
    #define N   5
    
    void foo( void *pointer ) 
    {
        uint8_t ( *matrix )[N][N][N][N] = pointer;
    
        for ( size_t i = 0; i < N; i++ )
        {
            for ( size_t j = 0; j < N; j++ )
            {
                for ( size_t k = 0; k < N; k++ )
                {
                    for ( size_t l = 0; l < N; l++ )
                    {
                        ( *matrix )[i][j][k][l] = N * ( i + j + k ) + l; 
                    }
                }
            }
        }
    }
    
    int main(void) 
    {
        uint8_t a[N][N][N][N];
    
        foo( &a );
    
        return 0;
    }