Let's say I have an array of pointers to structs. How do I make it so every element of the array points to a different memory location, so I can change these struct values through pointers individually?
Some example code:
struct Person {
int age;
char *name[64];
}
int main() {
struct Person *people[4];
struct Person tmp_person;
people[0] = &tmp_person;
people[0]->age = 12;
people[0]->name = "John";
people[1] = &tmp_person;
people[1]->age = 34;
people[1]->name = "Mike";
}
Here, every person element will be the same since all the array elements point to the same memory (tmp_person
). I know the code is incorrect, I'm just trying to make an example. So how do I make unique pointers? Creating a new variable for every element (tmp_person1
, tmp_person2
, ...) seems stupid and really hard.
As dbush said: The more typical case, and probably what you (don't know you) want is an array of objects, not only pointers to objects:
#include <stdio.h>
#include <stdlib.h>
struct Person {
int age;
const char *name;
};
void print_persons(const struct Person *persons, int arrSz)
{
for( int i=0; i<arrSz; i++)
{
printf("Person %s, age %d\n", persons[i].name, persons[i].age);
}
}
int main() {
struct Person people[2];
people[0].age = 12;
people[0].name = "John";
people[1].age = 34;
people[1].name = "Mike";
struct Person others[]
= { {23, "Jim"},
{24, "Joe"},
{25, "Jack"}
};
// Use pointers:
struct Person *peoplePtrs[2];
peoplePtrs[0] = malloc(sizeof(struct Person));
peoplePtrs[0]->age = 12;
peoplePtrs[0]->name = "JohnPtr";
peoplePtrs[1] = malloc(sizeof(struct Person));
peoplePtrs[1]->age = 34;
peoplePtrs[1]->name = "MikePtr";
print_persons(people, sizeof people/sizeof *people);
print_persons(others, sizeof others/sizeof *others);
for( int i=0; i<sizeof peoplePtrs/sizeof *peoplePtrs; i++)
{
printf("Person %s, age %d\n", peoplePtrs[i]->name, peoplePtrs[i]->age);
}
// good form to free the allocated memory, even though it is
// not really necessary at the end of a program
free(peoplePtrs[0]);
free(peoplePtrs[1]);
}
I corrected the type of name
to a simple pointer; that works best with static strings as in your example. You could use an array of chars but you'd have to initialize them with strcpy
or memcpy
— one cannot assign arrays.
I also showed you how to initialize the array directly which works if you know the data at programming time, as in your example.
You can surely use an array of pointers to structs, as shown in the last part; typically, the objects pointed to would be dynamically allocated with malloc (and later freed).
And I wrote a little function that prints a person just to show the contents.