将指针地址存储在分配的内存中 [英] 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.
我有一些未知类型的动态分配的内存,并希望在开始时在其中存储一个指针.malloc 返回的动态内存应该适当对齐,因此我认为在写入分配块的开头时不必担心对齐.
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.
这是我的代码,它可以工作,但我将指针表示为 64 位整数,并希望以更干净/可移植的方式进行:
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:
void *my_area = malloc(512);
void *my_pointer = get_my_pointer();
((long long *) my_area)[0] = (long long) my_pointer;
推荐答案
转换为 long long
只是额外的负担.改为转换为 void *
.
The cast to long long
is just extra baggage. Cast to void *
instead.
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, i.e., you don't need to use the structure at the same time.)
这篇关于将指针地址存储在分配的内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!