Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast void pointer to integer array

Tags:

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 to a memory address of size 100*300*2 = 60000 bytes

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

What i would like to achieve is to examine this memory as an integer array of size 100*150 = 15000 ints = 60000 bytes, like this:

unsigned int array[ 100 ][ 150 ]; 

I'm assuming it involves some casting though i'm not sure exactly how to formulate it. Any help would be appreciated.

like image 545
conor Avatar asked Jul 12 '12 14:07

conor


People also ask

Can we assign a void pointer to an int type pointer?

Now, we want to assign the void pointer to integer pointer, in order to do this, we need to apply the cast operator, i.e., (int *) to the void pointer variable. This cast operator tells the compiler which type of value void pointer is holding.

When can the void pointer being dereferenced?

A void pointer cannot be dereferenced. We get a compilation error if we try to dereference a void pointer. This is because a void pointer has no data type associated with it. There is no way the compiler can know what type of data is pointed to by the void pointer.


2 Answers

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; 
like image 68
nhahtdh Avatar answered Oct 11 '22 23:10

nhahtdh


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 
like image 41
podom Avatar answered Oct 11 '22 23:10

podom