c - 如何判断数组的某个位置是否为空?我遇到错误 :invalid operands to binary

标签 c

我不做太多 C 编程。我正在尝试使用该行

    if(strTable[key] ==NULL) 

找到空数组的位置。但是好像不行。 谁能告诉我这个错误的原因可能是什么?我认为这可能是一个地址,但我不知道该怎么做......

stringtable.h: In function `hasValue':
stringtable.h:32: error: invalid operands to binary ==
stringtable.h:37: error: invalid operands to binary !=
stringtable.h:39: error: invalid operands to binary !=

这是我的代码:

int hasValue(struct stringNode* strTable,char * s,int type)
{
   int key;
   struct stringNode currentNode;
   key = hash(s,type);
   if(strTable[key] == NULL) return 0;//line32
   currentNode = strTable[key];
   while(!(currentNode.content==s&&currentNode.datatype==type))
   {
      currentNode = strTable[currentNode.nextKey];
      if(currentNode) break;//line37
   }
   if(currentNode)//line39
      return 0;
   else
      return 1;
}

最佳答案

C 数组没有“空”元素。数组的每个元素都有一些值,并且该值属于数组声明的元素类型。

例如,给定:

int arr[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };

arr 的每个元素都有一些特定的 int 值。不存在“缺失”或“空”int 值。

如果您有一个指针数组,则某些元素可以包含空指针。如果您的程序逻辑将空指针视为“空”,那么这是完全合理的。 (说空指针是有效值也是合理的。)

在您的例子中,您显然有一个包含 struct stringNode 类型元素的数组。我们不知道 struct stringNode 是什么样子的。如果该类型有一些可测试的值,您的程序逻辑可以将其视为“空”,则可以使用它。如果没有,您将必须找到其他方法来指示空元素,或者重新构建您的程序,使其不依赖于将某些元素标记为空。

此外,您的错误消息(感谢您发布这些消息)表明您的函数定义位于头文件 stringtable.h 中。头文件应该只包含函数声明,例如:

int hasValue(struct stringNode* strTable,char * s,int type);

完整的定义可能应该在 stringtable.c 中,其中应该有一个 #include "stringtable.h" 指令。

有关如何构建 C 源文件的更多信息,但这超出了此问题的答案范围。如果你的教科书很不错,它应该对此进行解释。

关于c - 如何判断数组的某个位置是否为空?我遇到错误 :invalid operands to binary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9072631/

相关文章:

c - 实现循环冗余校验的程序错误

c - 访问结构指针的成员时取消引用指向不完整类型的指针

c - Massif 工具是否可以在多线程应用程序中正常工作?

c - 绑定(bind)失败 : Cannot assign requested address

C语言中正确释放双链接节点

c - “无论如何,遵循 "prefer++i over i++"指南,你就不会出错。” C语言中这背后的原因是什么?

c - 了解符号扩展

c - 移动所有线程以使用其他 CPU 核心,以便一个线程可以使用其他 CPU 核心?

c - 使用 fts(3) 遍历文件系统

c - 如何在 Linux 内核中打印 dst_entry 的内容