I'm trying to make a list of struct pointer using vector. My struct contains some fields like
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#define MAX 100
struct Student {
char* name,
*phoneNum,
*address
};
I have a utility function that helps init for struct pointer
struct Student* newStudent() {
struct Student* pStudent = NULL;
pStudent = (struct Student*)malloc(sizeof(struct Student));
pStudent->name = (char*)malloc(MAX * sizeof(char));
pStudent->phoneNum = (char*)malloc(MAX * sizeof(char));
pStudent->address = (char*)malloc(MAX * sizeof(char));
return pStudent;
}
inserting function is like
void insert(vector<Student*> &listStudents, Student* pStudent) {
printf("name: "); scanf("%s\n" , pStudent->name);
printf("phone number: "); scanf("%s\n", pStudent->phoneNum);
printf("address: "); scanf("%s\n", pStudent->address);
listStudents.push_back(pStudent);
printf("inserted OK!\n");
printf("Size: %lu\n", listStudents.size());
}
and display function
void display(vector<Student*>& listStudents) {
printf("total students: %lu\n", listStudents.size());
for (int i = 0; i < listStudents.size(); i++) {
printf("Student %d\n", i+1);
printf("name: %s\n", listStudents[i]->name);
printf("phone number: %s\n", listStudents[i]->phoneNum);
printf("address %s\n", listStudents[i]->address);
}
}
here is my main function
int main() {
Student* pStudent = newStudent();
vector<Student*> listStudents;
while(true) {
int op1;
printf("\n1. input\n2. output\n3. search\n4. erase\n5. end\n");
printf("option: ");
scanf("%d", &op1);
switch(op1) {
case 1:
insert(listStudents, pStudent);
break;
case 2:
display(listStudents);
break;
default:
printf("invalid option!\n");
break;
}
}
free(pStudent);
}
when I tried to insert some information into each field. It's was fine. But when I displayed it out. The results are duplicated. For example:
insert:
Student 1:
name: A
phone number: 010...
address: xyz
Student 2:
name: B
phone number: 011...
address: zyz
display the result was
Student 1:
name: B
phone number: 011...
address: zyz
Student 2:
name: B
phone number: 011...
address: zyz
What's wrong with that??
insertjust pushes the argument-provided student object pointer into the vector. You pass the same object pointer with each iteration, changing its content along the way. As a result, your vector is filled with (a) the same pointer duplicated over and over, and (b) the pointed-to object contains whatever was read last. Why you're mashing C and C++ concepts in this is a bigger mystery.Studentobjects are ever created in your code since the call tonewStudent()happens once.Studentstruct. Namely, a constructor, new instead of malloc, or better yet, just usestd::stringinstead ofchar*. Not to mentioncoutinstead ofprintf. You'll save many lines of code...