gpt4 book ai didi

c - 使用指向数组的结构体进行队列

转载 作者:行者123 更新时间:2023-11-30 16:40:10 26 4
gpt4 key购买 nike

在C中,我尝试学习队列数据结构并制作指向结构的指针,但在结构内部有指向数组的指针。这里queue是struct,q是指向struct的指针,struct内部有rearfrontnumint *que(指向存储数据的数组的指针)

typedef struct {
int max;
int rear;
int front;
int num;
int *que;
} queue;

malloc()使用

queue->que=malloc(sizeof(int)12) ; to make arrray And to access it, 
q->que[q->rear++] //not to familiar,

首先,我没有声明数组,但我可以使用 [] 访问 que 指向的数据吗?这是否意味着访问 q 指针内的 que[q->rear++] ?这与 (q).que[q->rear++] 相同吗?我遇到了段错误。

部分代码;但有一些错误

#include <stdio.h>
#include <stdlib.h>
typedef struct {
int max;
int num;
int front;
int rear;
int *que;
} queue;


int initialization(queue*q, int max) {
q->num = 0;
q->front = 0;
q->rear = 0;
if (q->que =(int*)malloc(max * sizeof(int)) == NULL) { // got pointer NULL i dont know why
q->max = 0;
return-1;
}
q->max=max;
return 0;
}


int main() {
queue que;
if (initialization(&que, 12) == -1)
printf("fail");
else {
int m,x;
while (m != 0) {
printf("1.enque 2.deque. 3.peek 4.display 0. slese");
scanf("%d", &m);
switch (m) {
case 0: break;
case 1: printf("data");
scanf("%d", &x);
enqueue(&que, x);
break;
case 2: dequeue(&que, &x);
printf("%d is dequeue", x);
break;
case 3:x=peek(&que,&x);
printf("max now is %d", x);
break;
case 4:display(&que);
}
}
}

int enqueue(queue*q, int x) {
if (q->num >= q->max)
return -1;
else{
q->num++;
q->que[q->rear++]= x; //got segmentation fault
if (q->rear == q->max)
q->rear = 0;
}
}

最佳答案

在您的 initialization() 函数中,同时使用 malloc() 分配内存,例如

if (q->que =(int*)malloc(max * sizeof(int)) == NULL) {

首先评估(int*)malloc(max * sizeof(int))部分,然后将this值与NULL进行比较通过 == 运算符。如果条件为假,则结果为 0,否则结果为 1

现在这个(01)值被分配给q->que而不是malloc() 的返回值。所以底线是 q->que 指向内存位置 0 (或 1 视情况而定),这很可能不是正常程序允许扰乱的内存部分,因此会出现错误。

您可以通过使用括号来解决此运算符优先级问题

if ((q->que = malloc(max * sizeof(int))) == NULL) {

main() 内的 while 循环中,控制表达式为 m!=0m > 在第一次迭代期间甚至没有初始化。此时,其值是不确定的(垃圾值)。

您可以首先将 m 初始化为 0 以外的内容,例如

int m=1,x;
while (m != 0) {

在 C 语言中,您无需转换 malloc() 返回的值。请参阅here .

关于c - 使用指向数组的结构体进行队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46782067/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com