c++ - 结构数组的内存分配错误

标签 c++ c pointers struct malloc

我正在编写这段代码:

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/

相关文章:

c - pthread_create 标识符

c - 从硬盘永久删除文件

c++ - C/C++ 向左或向右移动/偏移/移动位图?

c - 在数组中查找值范围时出错

c++ - ldap_set_option() 未设置选项 "LDAP_OPT_SSL"

c++ - 为什么 vector::operator[] 的实现方式与 map::operator[] 不同?

C++ 对给定列表中的每种类型执行一个操作

c++ - 我写的这个计算 NCR 的函数有什么问题吗?

C++ 问题 : pointers/memory addresses and subclasses

c - 如何在 C 中将 realloc 与双字符指针一起使用?