[英]Adding pointers to objects to a vector
I am trying to add pointers to an object to a vector in a function like this:我试图在这样的函数中将指向对象的指针添加到向量中:
vector:向量:
vector<struct Node*> vars;
function:功能:
void fill_vec(){
struct Node* temp;
temp = new Node();
cout << token << endl;
temp->name = token;
temp->value = 0;
cout << temp << endl;
vars.push_back(temp);
}
fill_vec is being called in a while loop that stops when there aren't anymore variable names. fill_vec 在 while 循环中被调用,当不再有变量名称时该循环停止。
It is adding the correct amount of nodes to the vector, but everything is pointing to the same object.它正在向向量添加正确数量的节点,但一切都指向同一个对象。 Token is being parsed.
正在解析令牌。
output of above:以上输出:
a
0x9c6010
b
0x9c6050
printing vector:印刷矢量:
void print_vars(){
for(int i = 0; i < vars.size(); i++){
cout << "Name:" << vars[i]->name << endl;
cout << "Value:" << vars[i]->value << endl;
}
}
output:输出:
Name:b
Value:0
Name:b
Value:0
My thought was that when I allocated new memory, the address would change.我的想法是当我分配新内存时,地址会改变。 When I print the address of temp each time I call the function, the address is the same .
每次调用函数都打印 temp 的地址时,地址是一样的。 I was printing the address wrong.
我把地址打印错了。 The address is different for each call of the function.
每次调用函数的地址都不同。 Thank you in advance for the help.
预先感谢您的帮助。
My thought was that when I allocated new memory, the address would change.
我的想法是当我分配新内存时,地址会改变。
It does indeed.确实如此。
When I print the address of temp each time I call the function, the address is the same.
每次调用函数都打印temp的地址时,地址是一样的。
That is because you are printing out the address of a local variable, which happens to reside at the same stack memory address each time fill_vec()
is called.那是因为您正在打印局部变量的地址,每次调用
fill_vec()
时,该地址恰好位于相同的堆栈内存地址。 You should be printing out the memory address of the allocated Node
instead.您应该打印出已分配
Node
的内存地址。
Change this line:改变这一行:
cout << &temp << endl;
To this:对此:
cout << temp << endl;
As it turns out, it was the token.事实证明,这是令牌。 Token is a char* and I was not using strdup() on it.
令牌是一个字符*,我没有在它上面使用 strdup() 。 So every time I updated token, name was being changed in each object.
所以每次我更新令牌时,每个对象中的名称都会发生变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.