Reputation: 111
My current code takes user input and collects student information. I am trying to write a function that will allow the user to add a new student. I reallocated the memory and passed everything into the function, but when I compile and run the program it outputs garbage for the new student instead of the new student details. Any help is appreciated.
Struct
struct student
{
char fname[20];
char lname[20];
float score;
};
Prototype
void addStudents(struct student *s, int student_size);
Main
int main()
{
int base_number, i;
int students;
struct student *ptr;
printf("Enter Number of Students: ");
scanf("%d", &base_number);
ptr = (struct student*)malloc(base_number * sizeof(struct student));
students = base_number;
printf("\nEnter Student Information\nExample: John Smith 98.50\n\n");
for(i = 0; i < base_number; i++)
{
printf("Student %d: ", i+1);
scanf("%s %s %f", (ptr+i)->fname, (ptr+i)->lname, &(ptr+i)->score);
}
printStudents(ptr, students);
students++;
ptr = realloc(ptr, students * sizeof(struct student));
addStudents(ptr, students);
//Getting garbage for new student
printStudents(ptr, students);
return 0;
}
addStudents Function
void addStudents(struct student *s, int student_size)
{
printf("\nAdd A Student\nStudent Information: ");
scanf("%s %s %f", (s+student_size)->fname, (s+student_size)->lname, &(s+student_size)->score);
}
Upvotes: 0
Views: 992
Reputation: 6230
Do not increase students
before you call addStudents
.
Otherwise it is out of the bounds of the array (and are editing a different student).
students++;
ptr = realloc(ptr, students * sizeof(struct student));
addStudents(ptr, students);
Should be
ptr = realloc(ptr, (students + 1) * sizeof(struct student));
addStudents(ptr, students);
students++;
Upvotes: 1
Reputation: 2676
students++;
ptr = realloc(ptr, students * sizeof(struct student));
addStudents(ptr, students);
AddStudents adds a student after the buffer. Either call
addStudents(ptr, students - 1);
Or change addStudents implementation to write to previous place in the buffer:
void addStudents(struct student *s, int student_size)
{
printf("\nAdd A Student\nStudent Information: ");
scanf("%s %s %f", (s+student_size-1)->fname, (s+student_size-1)->lname, &(s+student_size-1)->score);
}
Upvotes: 1