简体   繁体   English

将指针地址存储在分配的内存中

[英]Store pointer address in malloced memory

This feels like a silly question, but I just can't work out a clean solution and can't find a similar question in the mass of other pointer related questions.这感觉像是一个愚蠢的问题,但我无法找到一个干净的解决方案,也无法在大量其他与指针相关的问题中找到类似的问题。

I have some dynamically allocated memory of unknown type and want to store a pointer inside it at the start.我有一些未知类型的动态分配的内存,并希望在开始时在其中存储一个指针。 Dynamic memory returned by malloc should be suitably aligned so I don't think I have to worry about alignment when writing to the start of the allocated block. malloc 返回的动态内存应该适当对齐,因此我认为在写入分配块的开头时不必担心对齐。

This is my code, which works, but I'm representing a pointer as a 64-bit integer and want to do it in a more clean/portable way:这是我的代码,它有效,但我将指针表示为 64 位整数,并希望以更干净/可移植的方式进行:

void *my_area = malloc(512);
void *my_pointer = get_my_pointer();
((long long *) my_area)[0] = (long long) my_pointer;

The cast to long long is just extra baggage. long long的演员阵容只是额外的负担。 Cast to void * instead.改为转换为void *

void *my_area = malloc(512);
void *my_pointer = get_my_pointer();
((void **) my_area)[0] = my_pointer;

(I assume that this is for some kind of freelist or the like, ie, you don't need to use the structure at the same time.) (我假设这是针对某种自由列表之类的,即,您不需要同时使用该结构。)

What will be found in my_area[0] is pointer to something, right ?my_area[0]会发现什么是指向某物的指针,对吧?

Then you can allocate my_area to be of type void ** , which represent a pointer to a pointer containing memory area.然后,您可以将 my_area 分配为void **类型,它表示指向包含内存区域的指针的指针。

void **my_area = malloc(512 * sizeof(*my_area)); // alloc 512 pointer sized memory blocks
void *my_pointer = get_my_pointer();
my_area[0] = my_pointer;

Define a struct with internal array of 8 bytes.定义一个具有 8 个字节的内部数组的结构。 Replace all the long long type references with your custom struct.用您的自定义结构替换所有 long long 类型引用。 This way you will not depend on platform-specific size of long long.这样你就不会依赖于平台特定的 long long 大小。 The struct will be 64 bits on all platforms(you can add #pragma pack if you worry about alignment )该结构体在所有平台上都是 64 位(如果担心对齐,可以添加 #pragma pack)

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

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