0

キューへのポインタを 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;
}

また、次のように新しく作成されたキューに追加しようとします。

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;
}

メイン関数から:

int main()
{
    struct pqueue *queue;       

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

...しかし、私はセグメンテーション違反を続けています。これが起こり続ける理由は何ですか?

編集:

pqueue と node の構造体は次のようになります。

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

struct pqueue{
  struct node *root;
};
4

1 に答える 1

4

C では、すべてが値渡しされます。したがって、 を呼び出すと、ポインタのコピーcreateQueue(queue)が関数に渡されます。次に、関数内で と言うと、そのポインターのコピーを新しく割り当てられたメモリと等しくなるように設定しています。そのポインターの のコピーは変更されません。queue = malloc(...)main()

あなたはこのようなことをしたい:

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

int main(void)
{
    struct pqueue *queue;

    createQueue(&queue);
}

この質問には、何がうまくいかないかについてのより詳細な説明があります。

于 2013-10-09T19:22:59.940 に答える