I am trying to generate a code that is a phonebook, I have a person class with a name and number. I am generating the names and then later writing them to a file.
I create a vector of person pointers and then assign them in a separate function. I keep getting NULL though after the code executes. If I create this vector of person pointers and then pass it to a function that generates the person objects when the function ends do I lose these references? Shouldn't the new objects be created in the heap and still be there if they are referenced back to the vector? I would think the pointers get created in the stack of main and still be viable and then just get referenced to a place in the heap so I don't understand why I get NULL for all my values?
Here is my code:
int main(){
vector<Person*> people(10);
phone_gen(people);
return 1;
}
void phone_gen(vector<Person*> a){
cout << "Numbers generated \n";
a[0] = new Person("Mike", 6044219901);
a[1] = new Person("John" , 6041929402);
a[2] = new Person("Ted" , 6044211234);
a[3] = new Person("Stern", 6044211233);
a[4] = new Person("fred ", 6044211111);
a[5] = new Person("ben ", 6049999999);
a[6] = new Person("timmy", 6044211113);
a[7] = new Person("lowe ", 6044210908);
a[8] = new Person("Glenn", 6044217112);
a[9] = new Person("Danny", 6044211112);
}
The problem here is that you pass the argument by value , meaning the vector gets copied and the function only works on the copy and not the original.
You should pass the argument by reference instead:
void phone_gen(vector<Person*>& a)
// ^
// |
// Note ampersand here
In order to fill people
vector in the phone_get
function, you have to get it by reference:
void phone_get(vector<Person*>& a){...}
Otherwise, you will see 10 default constructed objects in the vector
(10 null pointers)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.