[英]C++ Vectors and struct pointers
我的結構有一個整數向量。 但是,當動態創建該結構的實例時,我似乎無法訪問該向量。
#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加到結構的向量上會使程序崩潰。 你好,世界! 從未顯示。 這是怎么回事?
只要將分配的內存區域簡單地轉換為astruct*
,就不會初始化向量,因此將不會調用struct的構造函數,因此不會調用std::vecotr
的構造函數。 請改用new運算符 。
astruct* myStruct = new astruct();
myStruct->intList.push_back(100);
delete myStruct;
除非您知道自己在做什么,否則不要在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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.