【问题标题】:Queue initializing function doesn't work队列初始化功能不起作用
【发布时间】:2018-06-30 13:26:37
【问题描述】:

我正在尝试使用数组实现队列,但是我的初始化函数似乎不起作用。甚至函数的第一行也没有执行。下面是结构体、函数和main:

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

typedef struct queue queue;

struct queue{
    int size, rear, front, length;
    int *arr;
};

queue* init(queue *queue1){
    queue1->size = 2;
    queue1->front = -1;
    queue1->rear = -1;
    queue1->length = 0;
    queue1->arr = (int*) malloc(sizeof(int)*queue1->size);
    return queue1;
}

int main(){
    queue* queue1 = init(queue1);
}

【问题讨论】:

    标签: c arrays data-structures queue


    【解决方案1】:

    你必须先为你的结构分配空间。

    像这样:

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct queue {
        int size, rear, front, length;
        int *arr;
    } queue;
    
    queue* init() {
        queue *queue1 = malloc(sizeof(queue));
        queue1->size = 2;
        queue1->front = -1;
        queue1->rear = -1;
        queue1->length = 0;
        queue1->arr = (int*) malloc(sizeof(int)*queue1->size);
        return queue1;
    }
    
    int main(){
        queue* queue1 = init();
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-19
      • 2020-11-29
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多