你好!现在我正在尝试用 C 编写一个 roguelike,同时我正在处理内存(非常有趣,在 python 和 sharpe 之后)。
有这样一段代码:
field- “二维”数组,里面存放的是迷宫
width和height,我想,
sizeret返回的点数组的长度是可以理解的
point *find_connectors(char *field, int width, int height, int *sizeret)
{
point *ret;
int size = 0;
for(int x = 0; x<width; x++)
for(int y = 0; y<height; y++)
{
char upper = get(x, y+1, field, width, height);
char bottom = get(x, y-1, field, width, height);
char left = get(x-1, y, field, width, height);
char right = get(x+1, y, field, width, height);
if(right != left && left != ' ' && right != ' ' ||
bottom != upper && bottom != ' ' && upper != ' ' ||
right != upper && right != ' ' && upper != ' ' ||
right != bottom && right != ' ' && bottom != ' ' ||
left != upper && left != ' ' && upper != ' ' ||
left != bottom && left != ' ' && upper != ' ')
{
if(ret == NULL)
{
size++;
ret = malloc(sizeof(point));
if(!ret)
{
printf("\n\n\n Bad memory error! Line %d\n\n\n", __LINE__);
exit(1);
}
ret[size-1] = new_point(x, y);
}
else
{
size++;
ret = realloc(ret, sizeof(point)*size);
if(!ret)
{
printf("\n\n\n Bad memory error! Line %d, size %d\n\n\n", __LINE__, size);
exit(1);
}
ret[size-1] = new_point(x, y);
}
}
}
*sizeret = size;
return ret;
}
它的作用:它遍历整个 characters 数组field,并在相邻的字符中寻找不同字符的点。这是生成迷宫所必需的。这些点被输入到一个数组ret中,它的长度是size,然后是sizeret。
但是在调用这个函数时,我总是得到一个错误(在 branch 中else)。该算法似乎有效,但在我将其移至单独的函数后问题就开始了。
我究竟做错了什么?
您的变量
ret未以任何方式初始化。循环内代码的逻辑与结果,您
ret最初包含一些非零垃圾,这会立即导致选择一个分支else,然后这些垃圾将在 中结束realloc。realloc下降。当然,您可以只替换
if (ret == NULL)为if (size == 0),因为size您没有忘记初始化。但最好换一种方式。首先,初始化你的
ret其次,事实上,你分成两个分支 -
malloc和realloc- 是额外的工作,经常在初学者的代码中发现。出于某种原因,他们认为有必要先做malloc,然后才有可能做realloc。事实上,
realloc空指针可以作为第一个参数传递给函数。在这种情况下, functionrealloc将等同于 functionmalloc。也就是说,在您的代码中,如果您最初在 in 中进行初始化ret,则可以完全删除NULL检查if (ret == NULL)和整个第一个代码分支 (c )。malloc第二个分支已经正确处理所有情况。当一个变量被定义而没有初始化时,它被默认初始化。一个对象的默认值取决于它被定义的位置。在函数体之外定义的变量被初始化为0。在函数体中定义的变量保持未初始化。点 *ret=nullptr; 显式初始化,你会很高兴)