简体   繁体   English

将void指针转换为整数数组

[英]Cast void pointer to integer array

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 基本上这就是我所拥有的,指向大小为100 * 300 * 2 = 60000字节的内存地址的指针

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: 我想要实现的是将此内存检查为大小为100 * 150 = 15000 ints = 60000字节的整数数组,如下所示:

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. 任何帮助,将不胜感激。

You can cast the pointer to unsigned int (*)[150] . 您可以将指针强制转换为unsigned int (*)[150] It can then be used as if it is a 2D array ("as if", since behavior of sizeof is different). 然后,它可以用作如果它是一个二维阵列(“如同”,由于行为sizeof是不同的)。

unsigned int (*array)[150] = (unsigned int (*)[150]) ptr;

Starting with your ptr declaration 从您的ptr声明开始

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. 您可以将ptr转换为指向您正在处理块的任何类型的指针,在本例中为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. 然后,通过解除引用然后索引来访问元素,就像访问普通的2d数组一样。

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

Some typedef s would help clean things up, too. 一些typedef也会帮助清理。

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应该正常工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM