Code:
#include "stdio.h"
struct person{
int personID;
//more stuff here later on
};
struct person *population[10];
int main(int argc, char *argv[]){
int i;
for(i = 0; i < 10; i++){
struct person p;
population[i] = &p;
population[i]->personID = i;
}
for(i = 0; i < 10; i++){
printf("Person Address: %d \n",*(population[i]));
printf("Person ID: %d \n",population[i]->personID);
}
}
First off, I'm fairly new to C and still trying to figure things out. I'm trying to create an array of pointers to person structs. I expected each iteration of the first for loop to create a new person struct with a new memory address. However it just seems to be giving me the same one every time. I've been reading up on structs, arrays, and pointers on google and I can't figure out why my code isn't working.
Output from second loop:
Person Address: 1606416904
Person ID: 9
Person Address: 1606416904
Person ID: 9
Person Address: 1606416904
Person ID: 9
Person Address: 1606416904
Person ID: 9
Person Address: 1606416904
Person ID: 9
Person Address: 1606416904
Person ID: 9
Person Address: 1606416904
Person ID: 9
Person Address: 1606416904
Person ID: 9
Person Address: 1606416904
Person ID: 9
Person Address: 1606416904
Person ID: 9
Could someone tell me how to get this working?