我正在编写这段代码:
struct box
{
char word[200][200];
char meaning[200][200];
int count;
};
struct root {
box *alphabets[26];
};
root *stem;
box *access;
void init(){
//cout<<"start";
for(int i = 0 ; i<= 25; i++){
struct box *temp =(struct box*)( malloc(sizeof(struct box)*100));
temp->count = 0;
cout<<temp->count;
stem->alphabets[i] = temp;
}
//cout<<" initialized";
}
它编译时没有错误,但在执行过程中它停止在 temp
分配给 stem->alphabets[i]
的位置。如何解决这个问题?
最佳答案
使stem
成为struct
,而不是指针:
root stem; // No asterisk
否则,没有分配给它的内存,因此取消引用它是未定义的行为。
当然你需要用stem.alphabets[i]
替换stem->alphabets[i]
。
关于c++ - 结构数组的内存分配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18802185/