Hi,
I am practicing the use of structs and malloc. The code below works fine whenever I try to read the data of a single person.
However, when I use a loop to fill my array with multiple people, the "read_new" function doesn't work anymore.
The second time, it skips the scanf that reads a name, and immediately wants to read the email.
Can anyone explain to me why this happens? And how I can fix / prevent this.
I am practicing the use of structs and malloc. The code below works fine whenever I try to read the data of a single person.
However, when I use a loop to fill my array with multiple people, the "read_new" function doesn't work anymore.
The second time, it skips the scanf that reads a name, and immediately wants to read the email.
Can anyone explain to me why this happens? And how I can fix / prevent this.
Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER 200
#define MAX 2
typedef struct{
char *name;
char email[25];
int age;
double weight;
}person;
person* read_new();
void print_people(person *people);
int main(int argc,char **argv){
int i;
person *people[MAX];
for(i=0;i<MAX;i++){
people[i] = read_new();
printf("Person %d has now been added to the array\n",i);
}
print_people(*people);
return 0;
}
person* read_new(){
person* temp;
char *buffer;
int length,age,weight;
temp = (person*)malloc(sizeof(person));
buffer = (char*)malloc(BUFFER*sizeof(char)+1);
printf("Name :");
scanf("%s",buffer);
length = strlen(buffer);
temp->name = (char*)malloc(length*sizeof(char)+1);
strcpy(temp->name,buffer);
printf("\nEmail :");
scanf("%s",buffer);
length = strlen(buffer);
strcpy(temp->email,buffer);
printf("\nAge :");
scanf("%d",&age);
temp->age = age;
printf("\nWeight :");
scanf("%l",&weight);
temp->weight = weight;
free(buffer);
return temp;
}
void print_people(person *people){
person *indexer = people;
while(indexer!=people+MAX){
printf("\nName = %s, email = %s, age = %d, weight = %f",indexer->name,indexer->email,indexer->age,indexer->weight);
indexer++;
}
}

