c - 链表节点初始化,不使用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;

我没有使用 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;

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

最佳答案

chunk* head, ptr 并没有按照您认为的那样进行。它相当于:

chunk *head;
chunk ptr;

你想要的是:

chunk *head;
chunk *ptr;

或者,如果你坚持的话,在一行中:

chunk *head, *ptr;

这里有一个链接,指向您在 C FAQ 上的问题.那里有更多评论和详细信息。

关于c - 链表节点初始化,不使用malloc(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26008012/

相关文章:

c - 如何使用带有双指针变量(没有支持变量)的结构字段?

c - 这个是casting吗,这个是什么and运算符

c - PortAudio - 在单声道中工作,在立体声中出现故障?

C dlsym undefined symbol

c - 可视化原始图像数据

c++ - 为什么内存管理很重要?

c++ - memcpy改变指针?

arrays - 为什么在使用指针访问未对齐的 uint16 数组时抛出 "alignment exception"而在使用下标访问数组时不抛出?

c# - 在 C# 中使不安全代码变得安全

c - 取消引用结构体中的数组(在 C 中)