gpt4 book ai didi

c - 在结构中初始化结构数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:33:53 25 4
gpt4 key购买 nike

我看过其他问题,但似乎找不到明确的答案。如何在结构内声明结构数组?我试图在 main() 中执行此操作,但我不知道我是否做对了,而且我不断收到此警告:“初始化从不强制转换的指针生成整数”

#define MAXCARDS 20     

struct card {
int priority;
};

struct battleQ {
struct card cards[MAXCARDS];
int head;
int tail;
int size;
};

int main (int argc, char *argv[]) {
struct battleQ bq;
bq.cards = {
malloc(MAXCARDS * sizeof (struct card)), //Trouble with this part
0,
0,
0
};

//...

return 1;
}

根据建议进行编辑:好的,现在我遇到了问题。我不断收到此错误:

3 [main] TurnBasedSystem 47792 open_stackdumpfile: Dumping stack trace to TurnBasedSystem.exe.stackdump

我不得不稍微更改代码并使所有内容都指向指针。我测试了它,一旦我尝试分配它的属性之一,它就会给我这个错误:bq->head = 0

整个过程只是将卡片添加到队列中。修改后的代码如下:

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

#define MAXCARDS 20

struct card {
int priority;
};

// A queue defined by a circular array
struct battleQ {
struct card *cards[MAXCARDS];
int head;
int tail;
int size;
};

bool battleQEnqueue (struct battleQ *bq, struct card *c);
bool battleQisFull(struct battleQ *bq);

// Method for enqueuing a card to the queue
bool battleQEnqueue (struct battleQ *bq, struct card *c) {
bool success = false;
if (battleQisFull(&bq)) {
printf("Error: Battle queue is full\n");
} else {
success = true;
bq->cards[bq->tail] = c;
bq->size = bq->size + 1;
bq->tail = (bq->tail + 1) % MAXCARDS;
}
return success;
}

int main (int argc, char *argv[]) {
int i;
struct battleQ *bq;
memset(&bq, 0, sizeof(bq)); // Did I do this properly?
bq->tail = 0; // Gives error at this point
bq->head = 0;
bq->size = 0;

// This is where I create a card and add it to the queue but the main problem
// is still the initialization above
for (i = 0; i < 5; i++) {
struct card *c = malloc(sizeof(c));
c->priority = i + 10;
printf("%d,", c->priority);
battleQEnqueue(&bq, &c);
}

return 1;
}

最佳答案

bq.cards 是结构数组,您不必 malloc 它。您可以将整个数组初始化为:

memset(bq.cards, 0, sizeof(bq.cards));

如果你想初始化bq

    memset(&bq, 0, sizeof(bq));

关于c - 在结构中初始化结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17258801/

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