【问题标题】:Issues with C linked listC链表的问题
【发布时间】:2017-10-22 23:55:48
【问题描述】:

我有一个函数可以将一个结构插入到一个作为链表实现的队列中。 我正在传递一个数组元素作为进程。

void q_insert (queue *q, process p) {
  printf("before insert attemp\n");
  if (q->head == NULL) {
    q->head = malloc(sizeof(struct Node));
    q->head->process = &p;
    q->head->next = NULL;
    q->tail = q->head;
    printf("After insertion into empty\n");
  }
  else {
    struct Node* temp;
    temp = malloc(sizeof(struct Node));
    temp->process = &p;
    temp->next = NULL;
    q->tail->next = temp;
    q->tail = temp;
    printf("after insertion into non empty\n");
  }
}

当我第一次在一个空列表上调用这个函数时,它似乎工作正常。当我尝试插入第二个项目时,它会添加第二个条目,但它也会用第二个条目的副本替换第一个条目。这些是使用的结构:

typedef struct {
  char name[80];
  int arrival_time;
  int execution_time;
  int priority;     // high number is high priority
} process;

struct Node{
  process* process;
  struct Node* next;
} q_node;

typedef struct {
  struct Node* head;
  struct Node* tail;
} queue;

【问题讨论】:

  • q->head->process = &p; : pq_insert 函数中的局部值。修复示例 E.g process* process; --> process process;.. q->head->process = p;
  • @BLUEPIXY 太棒了。谢谢。大约一年没用过 C 指针了。忘记的比我想象的要多。你现在正在救我。

标签: c linked-list


【解决方案1】:

C 只支持pass by value,当你通过指针传递变量的address 时,变量传递的地址的副本,以及在你的insert 函数中q == NULL 时,你正在分配内存并分配那个内存到q,但这不会在你的函数之外改变q:只有q的副本在你的函数内部会被改变。

为了更改参数q 指向的内容,并将这些更改反映在您的函数之外,您需要将指针传递给这样的指针:

void q_insert (struct node **q, process p) {
  if (q->head == NULL) {
  struct node* new_head = (struct node*)malloc(sizeof(struct node));
  new_head->head->next = NULL; 
  .
  .
  *q=new_head;
  .
  .
 }

【讨论】:

  • 我这样调用函数:q_insert(&wait_queue, list[next]);它似乎工作正常。我从wait_queue打印,信息是正确的。
  • 是的,这是正确的,因为 &wait_queue 是指向指针 queuestruct node 的指针
  • @krpra &wait_queue 是一个指向queue 指针的指针,为什么你说“或struct node”。 struct Nodequeue 是两种不同的 struct 类型。
  • wait_queue 是如何在这里声明的?如果是queue *wait_queue,我想应该没问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
  • 2013-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
相关资源
最近更新 更多