Cast void pointer to integer array

前端 未结 2 1058
死守一世寂寞
死守一世寂寞 2020-12-15 05:38

I have a problem where I have a pointer to an area in memory. I would like to use this pointer to create an integer array.

Essentially this is what I have, a pointer

相关标签:
2条回答
  • 2020-12-15 05:59

    You can cast the pointer to unsigned int (*)[150]. It can then be used as if it is a 2D array ("as if", since behavior of sizeof is different).

    unsigned int (*array)[150] = (unsigned int (*)[150]) ptr;
    
    0 讨论(0)
  • 2020-12-15 06:03

    Starting with your ptr declaration

    unsigned char *ptr = 0x00000000; // fictional point in memory goes up to 0x0000EA60
    

    You can cast ptr to a pointer to whatever type you're treating the block as, in this case array of array of unsigned int. We'll declare a new pointer:

    unsigned int (*array_2d)[100][150] = (unsigned int (*)[100][150])ptr;
    

    Then, access elements by dereferencing and then indexing just as you would for a normal 2d array.

    (*array_2d)[50][73] = 27;
    

    Some typedefs would help clean things up, too.

    typedef unsigned int my_2d_array_t[100][150];
    typedef my_2d_array_t *my_2d_array_ptr_t;
    my_2d_array_ptr_t array_2d = (my_2d_array_ptr_t)ptr;
    (*array_2d)[26][3] = 357;
    ...
    

    And sizeof should work properly.

    sizeof(array_2d); //4, given 32-bit pointer
    sizeof(*array_2d); //60000, given 32-bit ints
    sizeof((*array_2d)[0]); //600, size of array of 150 ints
    sizeof((*array_2d)[0][1]); //4, size of 1 int
    
    0 讨论(0)
提交回复
热议问题