I've looked at other questions but I can't seem to find a clear answer for this. How do I declare a struct array inside of a struct? I attempted to do it in main() but I don't know if I'm doing it right and I keep getting this warning: "initialization makes integer from a pointer without cast"
#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;
}
Edit after suggestions: Okay now I'm having problems. I keep getting this error:
3 [main] TurnBasedSystem 47792 open_stackdumpfile: Dumping stack trace to TurnBasedSystem.exe.stackdump
I had to change the code a bit and make everything pointers. I tested it and it gives me that error as soon as I try to assign one of its attributes like: bq->head = 0
The entire thing is just supposed to add a card to a queue. Revised code is below:
#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;
}