Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Dynamic array of pointers to array of structure

Tags:

c

I have a structure and a bidimensional array of those structs:

typedef struct {
char exit_n;
char exit_s;
char exit_w;
char exit_e;
} room;

room map[MAP_WIDTH][MAP_HEIGHT];

I need an array of pointers those structs. The following code compiles, but I don't get the wanted result. Any help? This is getting really confused to me, any explanation would be appreciated

room *rooms;
rooms = (room*)malloc(sizeof(room*) * ROOM_NUM);
[..]
rooms[n] = map[room_x][room_y];
[..]
like image 224
pistacchio Avatar asked Jan 07 '10 23:01

pistacchio


People also ask

Can you create an array of pointers to structures?

It is not possible to create an array of pointer to structures.

How do you dynamically allocate a struct?

To allocate a new person in the myperson argument, we use the following syntax: person * myperson = (person *) malloc(sizeof(person)); This tells the compiler that we want to dynamically allocate just enough to hold a person struct in memory and then return a pointer of type person to the newly allocated data.

Can you dynamically create an array in C?

We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.


1 Answers

Actually, I think you want

room** rooms;
rooms = (room**)malloc(sizeof(room*) * ROOM_NUM);
[..]
rooms[n] = &map[room_x][room_y];

This gives you an array of pointers to your rooms.

like image 175
Richard Pennington Avatar answered Sep 25 '22 21:09

Richard Pennington