结构中的二维数组 - 可能吗?
我正在尝试创建一个带有二维数组的结构来存储字符串。但是当我执行程序结构时,我不断收到双重释放错误
:
struct room{
int x;
int y;
char ** floor;
};
这是我的 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");
}
}
和我的 free,这似乎是导致错误的原因:
for(i=0; i<size ;i++)
{
free(toBeFreed->floor[i]);
}
free(toBeFreed->floor);
free(toBeFreed);
除了用字符填充数组之外,我并没有对数组做太多事情(使用 for 循环)并调用 mvprintw() 所以我不认为问题出在两者之间。我做错了什么?
编辑:所以我应该澄清,但是宽度==高度==大小,变量位于不同的文件中,所以它们确实有点不同
编辑2:显然高度!=宽度,我什至不能保持我自己的变量名直接!
I am attempting to make a struct with a 2D array in it to store strings. 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:
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. 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
EDIT2: apparently height != width, and I can't even keep my own variable name straight!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应该是
对的吗?
并且
应该是
+2
从哪里来?
除此之外,它看起来还不错,你能提供你想如何使用它的代码吗?
should be
right?
and
should be
Also
Where does the +2 come from?
Other than that it seems rather ok, can you supply code how you want to use it?
分配时使用:
释放时使用:
如果宽度!=大小,则会遇到问题。
When allocating you use:
When freeing, you use:
If width != size, you're going to have issues.