我试图弄清楚如果我通过内存位置如何初始化结构,下面的情况是我尝试做的,但它会抛出"无效初始化"缩写为相关代码
#ifndef PAGE_ALLOC_H
#define PAGE_ALLOC_H
typedef struct listNode
{
struct listNode *prev;
struct listNode *next; // prev/next element in linked list
char * address;
} listNode;
#endif
_____________________________________________
#include "page_alloc.h"
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char ** args)
{
void * memptr;
int test = posix_memalign(&memptr, 2, 128); // test is > 1, values such as 16 and 22 is this ok? It does seem to return a valid memory address though, but can't test until struct lets me initialize to it...
listNode testNode = memptr; // this throws improper initialization flag, but how else do I do tell //the struct where the eligible memory is?? Isn't that what malloc does? Return a point to acquired //memory
// Now this is what I imagine doing after telling testNode where its allocated memory
testNode ->prev = somePreviousNode; // etc.
}
我显然做错了什么但是什么?我很抱歉,如果这是一个愚蠢的问题,但我找不到任何posix_memalign的例子,也无法找到用指向已分配内存的指针正确初始化结构的解释。我需要动态添加节点,因为这是一个指向内存位置的双向链表(用于跟踪&#34;页面&#34;)
感谢任何见解!!!
答案 0 :(得分:2)
testNode
是结构的一个对象,你要为它指定一个指针(memptr
):
listNode testNode = memptr;
而是创建一个指向listnode的指针并为其分配已分配的内存:
listNode *testNode = memptr;
注意: alignment
参数的值应满足两个条件:
例如,
如果在您的计算机上sizeof(void*) = 4
,则可接受的值为4,8,16...
如果在您的计算机上sizeof(void*) = 8
,则可接受的值为8,16,32..
。