2

以下は、リンクリストを使用したキューの実装です。データ構造にまったく慣れておらず、キューのデータ構造を実装しようとしていました。このコードは正常にコンパイルされますが、実行しようとするとすぐにプログラムがクラッシュします。方法がわかりません。この問題を解決するために。何か手がかりがあれば、私のコードの何が問題になっているのか、私にアイ​​デアを教えてください。

助けてくれてありがとう。

これが私のCコードです:

#include<stdio.h>
#include<stdlib.h>
#define null 0
typedef struct node//node of a linked list
{
    int info;//info part of node
    struct node* next;// next pointer of a node
}*nodeptr;
typedef struct queue
{
    nodeptr front;//front pointer of a queue
    nodeptr rear;//rear pointer of a queue
} *QUEUE;

int empty_queue(QUEUE qwe)//if queue is empty then return 1
{
    if (qwe->front==null)
    return 1;
    else
    return 0;
}
void insert_queue( QUEUE qwe,int x)
{
    nodeptr p=(nodeptr)malloc(sizeof(struct node));//allocate new memory space to be added to queue
    p->next=null;
    p->info=x;
    if(empty_queue(qwe))//if the queue is empty,front and rear point to the new node
    {
    qwe->rear=p;
    qwe->front=p;
    return; 

    }
    qwe->rear->next=p;
    qwe->rear=p;
    //rear points to the new node
    return; 
}
int delete_queue(QUEUE qwe)
{   
    int x;
    if(empty_queue(qwe))//if queue is empty then it is the condition for underflow
    {
        printf("underflow\n");
        return;
    }
    nodeptr p=qwe->front;//p points to node to be deleted
    x=p->info;//x is the info to be returned
    qwe->front=p->next;
    if(qwe->front==null)//if the single element present was deleted
    qwe->rear=null;
    free(p);
    return x;

}
int main()
{
    int a;
    QUEUE qwe;
    qwe->rear=null;
    qwe->front=null;
    printf("enter values to be enqueued and -1 to exit\n");
    while(1)
    {
        scanf("%d",&a);
        if(a==-1)
        break;
        insert_queue(qwe,a);
    }
    printf("the values you added to queue are\n");
    while(!empty_queue(qwe))
    printf("%d\n",delete_queue(qwe));
    return 0;


}
4

1 に答える 1

4

QUEUE qwe;初期化されていないメモリへのポインタを宣言します。スタックのいずれかで、キューにメモリを割り当てる必要があります

struct queue qwe
qwe.rear=null;

またはヒープ上で動的に

QUEUE qwe = malloc(sizeof(*qwe));
qwe->rear=null;
...
free(qwe); /* each call to malloc requires a corresponding free */

typedefの後ろにポインタを隠すと、このタイプのbufを導入するのは非常に簡単です。QUEUE別の解決策は、タイプをに変更することですstruct queue。そうすれば、コード内の初期化されていないポインターに気付く可能性がはるかに高くなります。

于 2012-12-29T11:25:34.417 に答える