我的结构有一个整数向量。但是,当动态创建结构的实例时,我似乎无法访问该向量。
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
typedef struct {
vector<int> intList;
} astruct;
int main()
{
astruct* myStruct = (astruct*) malloc(sizeof(astruct));
myStruct->intList.push_back(100);
cout << "Hello world!" << endl;
free(myStruct);
return 0;
}
尝试向结构的向量添加100会导致程序崩溃。你好,世界!永远不会显示。发生了什么事?
答案 0 :(得分:4)
您的向量永远不会被初始化,因为您只是将已分配的内存区域转换为astruct*
,因此构造函数的构造函数因此永远不会调用std::vecotr
的构造函数。请改用 new operator 。
astruct* myStruct = new astruct();
myStruct->intList.push_back(100);
delete myStruct;
答案 1 :(得分:1)
您不应在C ++程序中使用malloc()
/ free()
,尤其是在创建C ++对象时,除非您知道自己在做什么。因此,请改用new
/ delete
:
int main()
{
astruct* myStruct = new astruct;
myStruct->intList.push_back(100);
cout << "Hello world!" << endl;
delete(myStruct);
return 0;
}