简体   繁体   English

尝试将struct传递给函数时保持段错误

[英]Keep segfaulting when trying to pass struct into function

I'm trying to pass a pointer to a queue into the createQueue function: 我正在尝试将指向队列的指针传递给createQueue函数:

void createQueue(struct pqueue *queue){
    queue = malloc( sizeof(struct pqueue) );  
    queue->root = malloc(sizeof(struct node));
    queue->root->next = 0;   
    queue->root->taskID = 12;
    queue->root->priority = 5000;
}

I also try to add to the newly created queue like this: 我还尝试像这样添加到新创建的队列中:

void add(struct pqueue *queue, int taskID, int priority){
struct node *conductor;
conductor = queue->root;
if ( conductor != 0 ) {
        while ( conductor->next != 0)
        {
                conductor = conductor->next;
        }
}
 conductor->next = malloc( sizeof(struct node) );  
 conductor = conductor->next;
 if ( conductor == 0 )
  {
      printf( "Out of memory" );
  }
  /* initialize the new memory */
  conductor->next = 0;         
  conductor->taskID = taskID;
  conductor->priority = priority;
}

from the main function: 从主要功能来看:

int main()
{
    struct pqueue *queue;       

    createQueue(queue);
    add(queue, 234093, 9332);
}

...but I keep segfaulting. ...但是我一直在断断续续。 Any reason why this keeps happening? 有什么原因会持续发生吗?

EDIT: 编辑:

The structs for pqueue and node are like this: pqueue和node的结构如下:

struct node {
  int taskID;
  int priority;
  struct node *next;
};

struct pqueue{
  struct node *root;
};

In C, everything is passed by value. 在C语言中,一切都是通过值传递的。 Therefore, when you call createQueue(queue) , you are passing a copy of the pointer to the function. 因此,当您调用createQueue(queue) ,您createQueue(queue)指针的副本传递给该函数。 Then, inside the function, when you say queue = malloc(...) , you are setting that copy of the pointer equal to your newly allocated memory - leaving main() 's copy of that pointer unchanged. 然后,在函数内部,当您说queue = malloc(...) ,您正在设置该指针的副本等于您新分配的内存-保持main()的指针副本不变。

You want to do something like this: 您想做这样的事情:

void createQueue(struct pqueue **queue)
{
    (*queue) = malloc( ... );
}

int main(void)
{
    struct pqueue *queue;

    createQueue(&queue);
}

This question has a more detailed description of what's going wrong for you. 该问题对您出了什么问题有更详细的描述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM