NULL pointer as marker of end of array

2019-07-22 17:09发布

问题:

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

Some structure:

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

Authors wrote about it:

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}
  };

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, ? }

What about not pointers?

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},
          {?,?,?}
      };

Thank you.

回答1:

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.

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).

Alternatively you could just pass a size_t around with it.



回答2:

You can invent special enum value (say, -1) which you would use as marker for last entry.



标签: c c89