2D array in a struct - is is possible?
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{
开发者_如何学Python 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!
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.
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?
Other than that it seems rather ok, can you supply code how you want to use it?
精彩评论