NULL指针作为数组的结束标志 [英] NULL pointer as marker of end of array

查看:274
本文介绍了NULL指针作为数组的结束标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了C语言程序设计第二版的6.3th段中,Kernigan&放大器;里奇。

I read the 6.3th paragraph of the "C programming language" second edition, by Kernigan & Ritchie.

一些结构:

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

作者写的:

量NKEYS是在密钥表的关键字的数量。虽然我们
  可以通过手算这个,这是一个极大的方便,更加安全,这样做
  机,尤其是如果该列表是随时可能更改。的一种可能性
  将终止初始化列表与空指针,
  然后沿密钥表循环,直到最后被找到。

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.

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

Everything would be clear if enum contained pointers only:

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

但每条记录还没有指针而已,但和 INT 太。如果我理解正确的作者,则最后一条记录必须像下面这样:

But the each record has not pointer only, but and int too. If I am right understand authors, then a last record must be like following:

{ NULL, ? }

什么不是指针?

我怎样才能解决这个问题的枚举,其中不包含指针?例如:

How can I solve it for enums, which don't contain the pointers? For example:

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

感谢您。

推荐答案

的一点是,通过设置最后一条记录为空,你可以通过它进行遍历时,平凡的标识阵列的结尾。

The point is that by setting the last record to be NULL you can trivially identify the end of the array when iterating through it.

在情况下,你没有指针,你仍然可以认为一些特殊的值来表示结束,也许计数指数永远不会在你的应用不利,所以看到一个小于0的值将是一个可能的标记,你可以用它来寻找可靠的结束。为结束标志的另一个常见的​​选择是 0〜(即全1)。

In cases where you don't have pointers, you could still deem some "special" value to indicate the end, perhaps count and index can never be negative in your application, so seeing a value less than 0 would be a possible marker that you can use to find the end reliably. Another common choice for end markers might be ~0 (i.e. all 1s).

另外,你可以只通过一个为size_t 与它周围。

Alternatively you could just pass a size_t around with it.

这篇关于NULL指针作为数组的结束标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆