c - NULL 指针作为数组结尾的标记

标签 c c89

我读了《C程序设计语言》第二版第6.3段,作者Kernigan & Ritchie。

一些结构:

struct key {
    char *word;
    int count;
} keytab[NKEYS] {
    { "auto", 0 },
    { "break", 0 },
    { "case", 0 },
    { "char", 0 },
    { "const", 0 },
    { "continue", 0 }
  };

作者写道:

The quantity NKEYS is the number of keywords in keytab. Although we could count this by hand, it’s a lot easier and safer to do it by machine, especially if the list is subject to change. One possibility would be to terminate the list of initializers with a null pointer, then loop along keytab until the end is found.

如果枚举只包含指针,一切都会很清楚:

struct key {
    char *word;
    char *description;
} keytab[NKEYS] {
    { "auto", "" },
    { "break", "" },
    { "case", "" },
    { "char", "" },
    { "const", "" },
    { "continue", "" }
    { NULL, NULL}
  };

但是每条记录不仅有指针,还有int。如果我对作者的理解是正确的,那么最后一条记录必须如下所示:

{ NULL, ? }

非指针呢?

对于不包含指针的枚举,我该如何解决?例如:

    enum myEnum {
        int index;
        inr count;
        double value;
    } myVariable[] {
          {0,0,0},
          {0,0,0},
          {0,0,0},
          {0,0,0},
          {?,?,?}
      };

谢谢。

最佳答案

要点是,通过将最后一条记录设置为 NULL,您可以在遍历数组时轻松识别数组的末尾。

在你没有指针的情况下,你仍然可以认为一些“特殊”值来指示结束,也许 countindex 永远不会是负数你的应用程序,所以看到一个小于 0 的值将是一个可能的标记,你可以使用它来可靠地找到结束。结束标记的另一个常见选择可能是 ~0(即全 1)。

或者,您可以随它传递一个 size_t

关于c - NULL 指针作为数组结尾的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14786888/

相关文章:

c - 什么是 TCACHE?

c - 我该如何修复 C 中的 if 语句以使其按预期工作?

c - memset + 空格 + memcpy

c - main 函数和之后的变量

c - 如何按照其他代码在 Visual Studio C89 中声明可变长度数组

c - snprintf 的隐式声明

php - 是否可以在 Windows 中的 PHP 和 C 之间共享内存?

c - 为什么下面的代码可以工作?

c - GLFW GLSL OPENGL问题

当已经以 "r+"模式打开时,在 C 中清除/截断文件