链接列表节点初始化,不使用malloc()

Mig*_*res 3 c malloc struct pointers linked-list

我有这个结构:

typedef struct chunk
{
  int size;
  int available;
  struct chunk* next;
} chunk;
Run Code Online (Sandbox Code Playgroud)

我初始化一个节点这样做:

chunk* head, ptr;

chunk* node = (chunk*) brkOrigin;
node->size = alloc - sizeof(chunk);
node->available = 1;
node->next = NULL;
Run Code Online (Sandbox Code Playgroud)

我没有使用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;
}
Run Code Online (Sandbox Code Playgroud)

错误:

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;
Run Code Online (Sandbox Code Playgroud)

对不起,如果这是一个愚蠢的问题(或一个愚蠢的错误),这是我第一次使用(主动)Stack Overflow.我无法理解这个错误.但我几乎可以肯定问题是没有malloc()的节点初始化...

Car*_*rum 8

chunk* head, ptr没有做你认为它正在做的事情.它相当于:

chunk *head;
chunk ptr;
Run Code Online (Sandbox Code Playgroud)

你想要的是:

chunk *head;
chunk *ptr;
Run Code Online (Sandbox Code Playgroud)

或者,如果你坚持,在一条线上:

chunk *head, *ptr;
Run Code Online (Sandbox Code Playgroud)

以下是C FAQ中确切问题的链接.那里有更多的评论和细节.