我想检查 tab[i][j + 1]
是否存在,它是一个 int **tab;
if (tab[i][j + 1] && tab[i][j + 1] == a_value)
tab[i][j + 1] = 1;
printf("%d\n", tab[i][j + 1]);
它会打印 a_value
但如果我取消 tab[i][j + 1]
if (/*tab[i][j + 1] && */tab[i][j + 1] == a_value)
tab[i][j + 1] = 1;
printf("%d\n", tab[i][j + 1]);
它打印我 1
。
为什么我不能检查 tab[i][j + 1]
是否存在?
这里是我把 map 放在数组中的地方
while (tmp != 22)
{
ln = read(fd, buff, 22);
buff[ln] = '\0';
while (buff[k] != '\0')
{
if (buff[k] == 'x')
tab[i][j] = WALL;
else if (buff[k] == ' ')
tab[i][j] = 0;
else if (buff[k] == 'e')
tab[i][j] = ENTRE;
else if (buff[k] == 's')
tab[i][j] = SORTIE;
k++;
j++;
}
k = 0;
tab[i][j] = -5;
j = 0;
i++;
tab[i] = malloc(sizeof(*tab) * 2000);
tmp++;
}
这是 map
xxxxxxxxxxxxxxxxxxxxx
xxx s
xxx xxxxxxxxxxxxxxxxx
xxx xxxxxxxxxxxxxxxxx
xxx xxxxx xxxxxxxxxxx
xxx xxxxx xxxxxxxxxxx
xxx xxxxx x
xx xxxxx x xxxxx x
xx xxxxxx xxx xxxxx x
xx xxx xxxxx x
xxxxxxxxx xxx xxxxx x
xxxxxx xxxxx x
xxxxxxxxx xxx xxx x
xxx xxxx xxx x
xxxxx xxx xxxxx xxx x
xxxxx xxx xxxx xxx x
xxx xxxx xxxx xx x
xxxx xxxxx xxxxx xx x
xxxx xxx xxxxx xx x
xxxx xxx xxx
xxxxxxxxexxxxxxxxxxxx
最佳答案
(因为有很多答案可以解释您的if
中的矛盾,我将跳过它。)
您无法检查 tab[i][j + 1]
是否存在,因为 C 不维护有关 (malloc
ed) 指针大小的信息 (好吧,除了指针大小,我说的是指针后面的缓冲区的大小)。如果 tab
是一个合适的数组,您可以使用 sizeof
来检查索引是否小于该值。但是当您将 tab
声明为 int **
时,此信息将丢失。
简而言之:需要在某处记录tab
的维度或者声明为数组,例如:
int tab[4][5];
然后您可以使用类似这样的方法来检查数组中的某个索引是否在边界内:
#define isAllocated(array, index) (index < sizeof(array))
并像这样使用它:
if(isAllocated(tab[i], j+1) && tab[i][j + 1] == 0){ ...
关于无法检查选项卡是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19518894/