简体   繁体   English

结构中的2D阵列-是否可能?

[英]2D array in a struct - is is possible?

I am attempting to make a struct with a 2D array in it to store strings. 我正在尝试制作一个带有2D数组的结构以存储字符串。 But I keep getting a double free error when I execute the program 但是当我执行程序时,我总是收到双重释放错误

struct: 结构:

    struct room{
        int x;
        int y;
        char ** floor;
};

Here is my malloc: 这是我的malloc:

struct room * newRoom = malloc(sizeof(struct room));
newRoom->floor = malloc(sizeof(char *) * height);
if(newRoom->floor == NULL || newRoom == NULL)
{
    printf("Room allocation failed \n");
}
for(i=0; i<width ;i++)
{
    newRoom->floor[i] = malloc(sizeof(char) * (width + 1));
    if(newRoom->floor[i] == NULL)
    {
        printf("Room string allocation failed \n");
    }
}

and my free, which is what seems to be causing the error: 和我的免费,这似乎是导致错误的原因:

for(i=0; i<size ;i++)
{
    free(toBeFreed->floor[i]);
}
free(toBeFreed->floor);
free(toBeFreed);

I don't really do much with the array other than fill it with characters (using for loops) and call mvprintw() so I don't think the problem is in between. 除了用字符填充数组(使用for循环)并调用mvprintw()之外,我实际上对数组没有做太多事情,因此我认为问题不在两者之间。 What am I doing incorrectly? 我做错了什么?

Edit: so I should've clarified but width == height == size, the variables are in different files, so they do differ a little 编辑:所以我应该澄清一下,但是width == height == size,变量在不同的文件中,所以它们的确有所不同

EDIT2: apparently height != width, and I can't even keep my own variable name straight! EDIT2:显然是height!= width,我什至不能保持自己的变量名直!

When allocating you use: 分配时使用:

for(i=0; i<width ; i++)

When freeing, you use: 释放时,您可以使用:

for(i=0; i<size ;i++)

If width != size, you're going to have issues. 如果width!= size,您将遇到问题。

for(i=0; i<width ;i++)

should be 应该

for(i=0; i<height;i++)

right? 对?

and

for(i=0; i<size ;i++)
{
    free(toBeFreed->floor[i]);
}

should be 应该

for(i=0; i<height;i++)
{
    free(toBeFreed->floor[i]);
}

Also

malloc(sizeof(char) * (width + 2));

Where does the +2 come from? +2来自哪里?

Other than that it seems rather ok, can you supply code how you want to use it? 除此之外,还可以,您能否提供代码以使其使用?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM