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
}
}
I am getting SEG FAULT error for this code while doing the malloc in for loop above….Any suggestions for any alternative to assign memory to the pointer in the vector of structs.
It is because you are trying to assign to a vector which does not have the elements yet. Do this instead:
That way you will be accessing actual memory.
In the comments the OP mentioned that the number of elements in the array will be decided at runtime. You can set
i < someVarwhich will allow you to decidesomeVarand the size of the list at runtime.The other answer
Is probably a better way to go though because it is likely that it will be more efficient.