无法检查选项卡是否存在

标签 c tabs

我想检查 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 不维护有关 (malloced) 指针大小的信息 (好吧,除了指针大小,我说的是指针后面的缓冲区的大小)。如果 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/

相关文章:

android - 我可以在 android 3.0 中显示没有操作栏的选项卡吗?

c++ - Fork off more processes as previous finish,直到达到最大值

python - 有没有办法将笔记本的标签设置在彼此下方?

c# - 如何在打开某些选项卡时停止运行保存按钮功能

c - 如何按名称(字符串)排序和搜索 BST?

java - 如何在我的 Activity 本身中使用 Bottom tabActivity

google-chrome - 谷歌浏览器 : refresh duplicate tab

c - 我的 C 程序没有检测到键盘输入

C: scanf 和程序退出

c - 具有更多解的线性方程的算法