'How do I dynamically allocate memory to a struct with data?
Lets say I have a program with a struct
typedef struct Room {
char* name;
struct Room * North;
struct Room * South;
struct Room * East;
struct Room * West;
struct Item * itemList;
char *character[10];
} Room;
And I have to create a bunch of them, as well as dynamically allocate memory for them. As I am new to this, there might be some obvious answers that I might not have known, but how can I assign memory to these structs, while also assigning values to them at once? I know there are ways to do so by declaring a pointer and then manually assigning data using ->, but I want to use the format I have given below, as it would be difficult to assign data one value at a time.
struct Room* room1p = (struct Room*) malloc(sizeof(struct Room));
struct Room* room2p = (struct Room*) malloc(sizeof(struct Room));
struct Room* room3p = (struct Room*) malloc(sizeof(struct Room));
struct Room room1, room2, room3;
room1 = (Room){roomList[1], NULL, &room3, &room2, NULL, itemRoom1, charList[1]};
room2 = (Room){roomList[2], NULL, &room2, &room3, &room1, itemRoom2, charList[2]};
room3 = (Room){roomList[3], NULL, &room1, NULL, &room2, itemRoom3, charList[3]};
Solution 1:[1]
There is not a built-in way to do this in C. Allocating memory is a separate action from initializing said memory with a value.
You could assign the allocation and initialization to a function if you want to be able to do both in one line:
struct Room* room_alloc_and_init(char* name, struct Room* north,
struct Room* south, struct Room* east,
struct Room* west, struct Item* item_list,
char** character)
{
// Allocate
struct Room* new_room = (struct Room*) malloc(sizeof(struct Room));
// Initialize
new_room->Name = name;
new_room->North = north;
new_room->South = south;
new_room->East = east;
new_room->West = west;
new_room->itemList = item_list;
new_room->character = character;
return new_room;
}
// Later on
struct Room* room1 = room_alloc_and_init(...);
// Be sure to free your memory when you are done with it!
free(room1);
// Also free any of the pointers you passed to room_alloc_and_init
// if they point to heap allocated memory
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
