c - How to assign a array to a pointer in a struct? -



c - How to assign a array to a pointer in a struct? -

i have next structs example:

#define max_people 16 typedef struct { int age; }person; typedef struct { person *people; int numpeople; }team;

i'm trying allocate array of persons in function, passed parameters. team supposed store array of 16 pointers of person. can't figure out i'm doing wrong.

void initiateteam(team * team){ team->numpeople = max_people; person *p[max_people]; for(int i=0; i<max_people;i++){ p[i] = malloc(sizeof(person); } team->people = &p[0]; }

i printed out addresses of team->people[i] , i'm getting random junk. why assingment team->people = &p[0] wrong? shouldn't first address of array perform pointer arithmetic?

since in comments stated you're trying allocate array of person objects , not pointers, should rather do:

void addpeople(team * team){ team->numpeople = max_people; team->people = malloc(sizeof(person) * max_people); }

mind there's no * in sizeof since don't want array of pointers of objects. later able access single elements (i.e. each person object) with

team->people[2].age = 25; // 3rd person in array

finally, remember free memory.

c pointers

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -