You can try something like this, but it really depends on how you are gathering you're data. But with the array you have described it is possible this way.
Although, for you're specific situation, where you have declared 7
persons, it is best to not use malloc()
. If you don't know how many persons there will be, then malloc()
is a good choice.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HOW_MANY 7
typedef struct{
char *name;
int age;
}person_t;
typedef struct {
person_t *person;
int numpersons;
} all_person_t;
all_person_t *initialize_persons(void);
void insert(all_person_t *persons, char *name, int age, int count);
void print_persons(all_person_t *persons);
void insert_each_person(all_person_t *persons, char *names[], int ages[]);
void free_persons(all_person_t *persons);
int
main(int argc, char const *argv[]) {
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim", "Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
all_person_t *persons;
persons = initialize_persons();
insert_each_person(persons, names, ages);
print_persons(persons);
free_persons(persons);
return 0;
}
void
insert_each_person(all_person_t *persons, char *names[], int ages[]) {
int i;
persons->person = malloc(persons->numpersons *sizeof(person_t));
for (i = 0; i < persons->numpersons; i++) {
insert(persons, names[i], ages[i], i);
}
}
all_person_t
*initialize_persons(void) {
all_person_t *persons;
persons = malloc(sizeof(*persons));
persons->numpersons = HOW_MANY;
return persons;
}
void
insert(all_person_t *persons, char *name, int age, int count) {
persons->person[count].name = malloc(strlen(name)+1);
strcpy(persons->person[count].name, name);
persons->person[count].age = age;
}
void
print_persons(all_person_t *persons) {
int i;
for (i = 0; i < persons->numpersons; i++) {
printf("%s %d\n", persons->person[i].name, persons->person[i].age);
}
}
void
free_persons(all_person_t *persons) {
int i;
for (i = 0; i < persons->numpersons; i++) {
free(persons->person[i].name);
}
free(persons->person);
free(persons);
}