Home > Back-end >  Array of struct in C, char**
Array of struct in C, char**

Time:04-22

I was looking forward to make an array of struct just like [ obj, obj, obj ]. I got this struct:

struct obj {
    char name[MAX_NAME];
    char desc[MAX_TEXT];
    bool asible;
};

How can I make it?

I tried

struct obj **objInRoom = malloc(sizeof(struct obj));

But when I iterate in it, it doesnt have anything :D I chose this solution because I need to put that array of struct into this struct:

struct room {
    struct obj **objts;     //HERE
    int qntty_objts;
    struct interact **interacts;
    int qntty_interacts;
};

CodePudding user response:

If you need to have a double pointer for some reason, then you can do something like this struct obj *objInRoom = malloc(sizeof(struct obj)); and then assign address of objInRoom to your struct room->objts=&objInRoom.

CodePudding user response:

struct obj **objInRoom = malloc(sizeof(struct obj));

If I simplifies, in your try you are allocating an area for a struct and trying to assign its address to a 'struct obj address' address holder which is struct obj**. But you should use struct obj * to hold the address of newly allocated area.

Which in this case your struct room should be like this:

struct room {
    struct obj *objts;     //struct obj** to struct obj*
    int qntty_objts;
    struct interact **interacts;
    int qntty_interacts;
};

You should assign your newly allocated area like this:

struct obj *objInRoom = (struct obj*)malloc(sizeof(struct obj));

But in this case you only allocated the area for one struct obj element. To increase this area you can take the backup of your previous data and allocate new area for more size. For example to increase your allocated area two times:

//cap is integer defined before to hold capacity information of array
struct obj *backup = (struct obj*)malloc(2*cap*sizeof(struct obj));
for(int i = 0; i < cap;   i)
    backup[i] = objInRoom[i];
free(objInRoom); //to prevent memory leak, because we allocated new area for our incremented sized array.
objInRoom = backup;
cap *= 2;

Or you can simply use realloc to increase your array capacity if an allocation happened before with malloc or calloc, realloc creates an array with desired size and holds the previous data:

objInRoom = (struct obj*)realloc(objInRoom, 2*cap*sizeof(struct obj))

Note: Always cast your malloc operation to your desired pointer type because it returns 'void *' for default.

Note 2: Always check outputs from malloc, realloc and calloc; they return NULL in case of error.

  • Related