struct LeafDataEntry
{
void *key;
int a;
};
int main(){
//I want to declare a vector of structure
vector<LeafDataEntry> leaves;
for(int i=0; i<100; i++){
leaves[i].key = (void *)malloc(sizeof(unsigned));
//assign some value to leaves[i].key using memcpy
}
}
在上面的 for 循环中执行 malloc 时,我收到此代码的 SEG FAULT 错误....关于将内存分配给结构 vector 中的指针的任何替代方法的任何建议。
最佳答案
这是因为您正试图分配给一个还没有元素的 vector 。改为这样做:
for(int i=0; i<100; i++){
LeafDataEntry temp;
leaves.push_back(temp);
leaves[i].key = (void *)malloc(sizeof(unsigned));
//assign some value to leaves[i].key using memcpy
}
这样您将访问实际内存。
OP 在评论中提到数组中元素的数量将在运行时决定。你可以设置i < someVar
这将允许您决定 someVar
以及运行时列表的大小。
另一个答案
leaves.resize(someVar) //before the loop
虽然这可能是一种更好的方法,因为它可能会更有效率。
关于c++ - 将内存分配给结构 vector 指针时出现 SEG FAULT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13389268/