一个简单的链式队列,运行程序总报错。

链式队列程序,不知道哪里出问题了,报错。萌新求解答。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef int elemtype;
struct Node{
    struct Node *next;
    elemtype data;
};
typedef struct Node node;
node* getnode(elemtype x,node* nextptr){
    node* n;
    n=(node*)malloc(sizeof(node));
    n->data=x;
    n->next=nextptr;
    return n;
}

typedef struct{
    node* front;
    node* rear;
    int length;

}queue;

void  initqueue(queue* q){
    q=(queue*)malloc(sizeof(queue));
    q->front=getnode(0,NULL);
    q->rear=q->front;
    q->length=0;
}

void insertafter(node* n,node* p){
    p->next=n->next;
    n->next=p;
}



void in(queue* q,elemtype x){
    node* newnode;
    newnode=getnode(x,NULL);
    if(q->length==0)
        insertafter(q->front,newnode);
    insertafter(q->rear,newnode);
    q->rear=newnode;
    q->length++;
}

elemtype out(queue* q){
    node* n;
    elemtype x;
    x=((q->front)->next)->data;
    n=q->front;
    q->front=(q->front)->next;
    free(n);
    q->length--;
    return x;
}

void main(){
    queue* q;
    initqueue(q);
    int array[20];
    memset(array,0,sizeof(array));
    for(int i=0;i<=50;i++)
        in(q,i);
    for(int j=0;j<20;j++)
        array[20-j]=out(q);
    for(int k=0;k<=19;k++)
        printf("%d\n",array[k]);
    system("pause");


}

for(int j=0;j<20;j++)
array[20-j]=out(q);
这里循环有问题?

看我给你的注释

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef int elemtype;
struct Node{
    struct Node *next;
    elemtype data;
};
typedef struct Node node;

node* getnode(elemtype x,node* nextptr){
    node* n;
    n=(node*)malloc(sizeof(node));
    n->data=x;
    n->next=nextptr;
    return n;
}
typedef struct{
    node* front;
    node* rear;
    int length;
}queue;

void  initqueue(queue* q){
    q=(queue*)malloc(sizeof(queue));
    q->front=getnode(0,NULL);
    q->rear=q->front;
    q->length=0;
}

void insertafter(node* n,node* p){
    p->next=n->next;
    n->next=p;
}
void in(queue* q,elemtype x){
    node* newnode;
    newnode=getnode(x,NULL);
//  if(q->length==0)
//      insertafter(q->front,newnode);
//  insertafter(q->rear,newnode);
//  q->rear=newnode;
}

elemtype out(queue* q){
    node* n;
    elemtype x;
//  x=((q->front)->next)->data;
//  n=q->front;
//  q->front=(q->front)->next;
//  free(n);
//  q->length--;
    return x;
}

void main(){
    queue* q;
    initqueue(q);
    int array[20];
    memset(array,0,sizeof(array));
    for(int i=0;i<=50;i++)      
        in(q,i);
    for(int j=0;j<20;j++)
        array[20-j]=out(q);
    for(int k=0;k<=19;k++)
        printf("%d\n",array[k]);
    system("pause");
}