链表节点初始化,不使用malloc()
我有这个结构:链表节点初始化,不使用malloc(),c,pointers,struct,linked-list,malloc,C,Pointers,Struct,Linked List,Malloc,我有这个结构: typedef struct chunk { int size; int available; struct chunk* next; } chunk; 我初始化一个节点,执行以下操作: chunk* head, ptr; chunk* node = (chunk*) brkOrigin; node->size = alloc - sizeof(chunk); node->available = 1; node->next = NULL; 我没
typedef struct chunk
{
int size;
int available;
struct chunk* next;
} chunk;
我初始化一个节点,执行以下操作:
chunk* head, ptr;
chunk* node = (chunk*) brkOrigin;
node->size = alloc - sizeof(chunk);
node->available = 1;
node->next = NULL;
我没有使用malloc(),因为这是一个赋值,我必须实现myMalloc(),所以brkOrigin是我在代码之前使用sbrk()得到的地址。这就是为什么我使用这个直接地址而不是malloc()。但我不知道这样做是否正确,如果有人知道如何在没有malloc()的情况下初始化喜欢列表的节点,那也很好
但我必须搜索链接列表,在尝试此操作时出现了一些错误:
head = node;
ptr = head;
while(ptr != NULL)
{
if(ptr->size >= mem && ptr->available == 1)
{
ptr->available = 0;
if(ptr->size > mem)
{
//Split in two nodes. Basically, create another with the remainder of memory.
}
}
else
ptr = ptr->next;
}
错误:
error: incompatible types when assigning to type ‘chunk’ from type ‘struct chunk *’
ptr = head;
error: invalid operands to binary != (have ‘chunk’ and ‘void *’)
while(ptr != NULL)
error: invalid type argument of ‘->’ (have ‘chunk’)
if(ptr->size >= mem && ptr->available == 1)
error: invalid type argument of ‘->’ (have ‘chunk’)
if(ptr->size >= mem && ptr->available == 1)
error: invalid type argument of ‘->’ (have ‘chunk’)
ptr->available = 0;
error: invalid type argument of ‘->’ (have ‘chunk’)
if(ptr->size > mem)
error: invalid type argument of ‘->’ (have ‘chunk’)
ptr = ptr->next;
抱歉,如果这是一个愚蠢的问题(或愚蠢的错误),这是我第一次使用(主动)堆栈溢出。我不能理解这个错误。但我几乎可以肯定,问题在于没有malloc()的节点初始化…
chunk*head,ptr
没有做您认为它正在做的事情。这相当于:
chunk *head;
chunk ptr;
您想要的是:
chunk *head;
chunk *ptr;
或者,在一行中,如果您坚持:
chunk *head, *ptr;
这里有一个链接,指向您目前的问题。这里有更多的评论和详细信息。哦!谢谢你的清楚解释,帮了我很大的忙!除此之外,不使用malloc()初始化节点还可以吗?我认为没有足够的代码可以确定。