Hey everyone, I’ve been having some trouble in C, i’m using a variety of array nested structs in order to model a universe. Here is the struct code…
struct star
{
int x;
int y;
int z;
int m;
char name[100];
};
struct colony
{
int pop;
};
struct planet
{
int x;
int y;
int z;
int m;
int colonized;
char name[100];
struct colony colony_member;
};
struct galaxy
{
int x;
int y;
int z;
char name[100];
struct planet planet_member;
struct star star_member;
};
Let’s say I made 10 random galaxies with random values in the struct, how would I create 100 planets within that galaxy struct? I’m confused as how the best way to handle this would be, or even if structs if the way I want to go.
Thanks in advance!
-Devan
You have several options available, starting with the easiest:
and to create a galaxy:
Don’t forget, you need to
freethe memory youmalloc, otherwise you’ll get a memory leak.You could use more complex data structures, like a linked list. So, your galaxy struct has a pointer to the first and last planet in the list. Each planet has a pointer to the next and previous planet in the list. So starting with the first planet and reading the next planet pointer you can process each planet in the list. Look up linked list on Google to find more information about it. It’s a lot more work, and work that’s been done many times already, which leads to….
…progressing to C++ where there’s a standard library that can do all the fiddly housekeeping of linked lists and other data types for you. So, your structure would become:
But, you could go further still and make galaxy a C++ class so that when you create one, it automatically creates the planets and stars in it, and when you get free it, the class automatically frees all the planets and stars it holds.