SEG 错误,同时将内存分配给结构向量的指针
SEG FAULT while assigning memory to the pointer of vector of structs
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 错误错误......有关将内存分配给结构向量中的指针的任何替代方法的任何建议。
这是因为您正在尝试分配给尚未具有元素的向量。请改为执行以下操作:
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
这可能是一个更好的方法,因为它可能会更有效率。
您正在索引一个空向量。尝试使用
leaves.resize(100);
循环之前。
相关文章:
- 将结构向量排序为子组
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 如何在 c++ 中创建结构向量的映射
- 带unique_ptr的结构向量
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 将信息输入到下面显示的结构向量中的正确语法/格式是什么
- C++对结构向量进行排序
- 在C++中对结构向量进行排序时出现问题
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- 搜索并替换结构向量中的值
- 在结构向量中查找最接近的值
- 清除结构向量时会发生什么?
- 如何从 node-ffi 调用 c++ 中以结构向量作为参数的方法?
- 对结构向量进行两次排序
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 如何二进制搜索结构向量并在适当的索引处插入
- 结构向量中自定义结构函数的内存使用
- C++11-在结构向量中修改结构的成员
- 我正在尝试找到一个特定的结构成员,该成员是使用 lambda 函数的结构向量
- 在结构向量中搜索一个数据成员,然后打印匹配的所有数据成员