C++ 将内存分配给结构向量指针时出现SEG错误 struct-LeafDataEntry { 无效*键; INTA; }; int main(){ //我想声明一个结构向量 向量叶; 对于(int i=0;i
而言,这是因为您试图分配给一个尚未包含元素的向量。请改为:C++ 将内存分配给结构向量指针时出现SEG错误 struct-LeafDataEntry { 无效*键; INTA; }; int main(){ //我想声明一个结构向量 向量叶; 对于(int i=0;i,c++,vector,segmentation-fault,std,C++,Vector,Segmentation Fault,Std,而言,这是因为您试图分配给一个尚未包含元素的向量。请改为: 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 *
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
}
}
这可能是一种更好的方法,因为它可能会更有效。这是因为您试图分配给一个尚未包含元素的向量。请改为:
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
}
}
可能是一种更好的方法,因为它可能会更有效。您正在为空向量编制索引。请尝试使用
leaves.resize(someVar) //before the loop
在循环之前。您正在索引一个空向量。请尝试使用
leaves.resize(someVar) //before the loop
在循环之前。向量怎么知道它应该包含100个元素?你的
键最终将存储什么,什么类型的数据?@KerrekSB,Omg我喜欢这个链接。现在它很容易记住。@KerrekSB:有趣,因为在这种情况下是使用std::vector
导致segfault…@Anonymous-p问题是离开[i]
不存在。到目前为止提供的两个答案解决了这个问题。向量应该如何知道它应该包含100个元素?你的键
最终将存储什么类型的数据?@KerrekSB,Omg我喜欢这个链接。现在它很容易记住。@KerrekSB:有趣,因为它使用的是std::vector
在本例中,由于segfault…@Anonymous-问题是离开[i]
不存在。目前提供的两个答案解决了这个问题。