简体   繁体   English

结构内部的向量,如果struct的对象是动态创建的,则我们不能将向量中的元素推入

[英]vector inside a structure if the object of struct is dynamically created then we cannot push elements in the vector

struct node
{
    vector<int> v;
};  
//case 1:

struct node *t = (struct node *) malloc(sizeof(struct node));  

t->v.push_back(4);// segmentation fault

//case 2:
struct node t;
t.v.push_back(6);

I know the reason of segmentation fault in first case we have dynamically allocated memory . 我知道第一种情况下分段错误的原因是我们动态分配了内存。 then we are trying to use the memory which is not allocated. 那么我们正在尝试使用未分配的内存。 In second case we are using stack memory. 在第二种情况下,我们使用堆栈存储器。 can you explain it more clearly ? 你能更清楚地解释吗? sry for bad style of asking doubt , i am newbie 不好意思问我,我是新手

use new instead of malloc . 使用new而不是malloc

The default constructor of the struct is not called when using malloc , then the vector is not initialized. 该结构的默认构造函数不叫当使用malloc ,则vector未初始化。

As vector is a class with a non-trivial constructor , so the struct has a non-trivial constructor, it can not be ignored. 作为载体是具有一类非平凡的构造 ,所以结构有一个不平凡的构造函数,它不能被忽略。

Remember to delete the pointer after using to avoid memory leak. 请记住使用,以避免内存泄漏后删除指针。

What Matt said. 马特说的。

Not only is the vector not initialized, but the region of memory occupied by your struct is not set to anything by malloc. 不仅不初始化向量,而且malloc还没有将结构占用的内存区域设置为任何值。 You can't even count on it being cleared to zero, it will be whatever the previous user of that region of memory put there. 您甚至无法指望将其清除为零,这将是该内存区域的先前用户所处的位置。

 struct node *t( new struct node );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM