Reputation: 305
I just started programming in C a few days ago. I am now trying to learn structs.
I have this program and I want to improve it so that my array people is now an array of pointers to structs. I am not sure how to do this.
I also want to modify my insert method, to call malloc to create a new struct and set the correct array element pointing to it.
As far as I know, malloc is dinamic memory allocation but although I've read some guides I'm still unsure on how exactly to use it. Also, after using malloc, what else do I need to change in my program for it to work as before?
Upvotes: 0
Views: 3089
Reputation: 21233
If you want people
to be an array of pointers, you have to declare it like this:
struct person *people[12];
Remember that declaration follows use and that dereferencing has lower precedence than array indexing; this means that *people[i]
is of type struct person
, and thus, people[i]
is a pointer to struct person
.
To initialize each position in people
, you call malloc()
to make your pointers point to a valid memory location large enough to hold a struct person
. It is as easy as:
people[i] = malloc(sizeof(struct person));
When you don't need people
anymore, you have to remember to free every memory position you allocated, by calling free(people[i])
for every position i
.
I noticed you declared the array to hold 12 structs. This can be dangerous when someone changes the code: it will not work when HOW_MANY
is greater than 12. You should declare an array of the same size:
struct person *people[HOW_MANY];
This ensures that your array always has exactly the space needed.
UPDATE:
You need to declare insert
as receiving an array of pointers instead of an array of structures:
static void insert (struct person *people[], char *name, int age) { ... }
And people[i].name
is invalid. Since people[i]
is a pointer now, you need to do it like this:
people[i]->name
Or, equivalently, (*people[i]).name
.
The same applies to people[i]->age
. Remember to change this both in main()
and inside insert
.
Also, consider passing i
to insert
instead of using static
variables, unless you have a very good reason to do so. Static variables are used for functions with internal state, and for me, insert
is not quite the type of function where you'd want that.
Upvotes: 1