What does it mean to be “terminated by a zero”?

前端 未结 7 602
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 17:21

I am getting into C/C++ and a lot of terms are popping up unfamiliar to me. One of them is a variable or pointer that is terminated by a zero. What does it mean for a space

相关标签:
7条回答
  • 2020-12-06 18:12

    While the classic example of "terminated by a zero" is that of strings in C, the concept is more general. It can be applied to any list of things stored in an array, the size of which is not known explicitly.

    The trick is simply to avoid passing around an array size by appending a sentinel value to the end of the array. Typically, some form of a zero is used, but it can be anything else (like a NAN if the array contains floating point values).

    Here are three examples of this concept:

    1. C strings, of course. A single zero character is appended to the string: "Hello" is encoded as 48 65 6c 6c 6f 00.

    2. Arrays of pointers naturally allow zero termination, because the null pointer (the one that points to address zero) is defined to never point to a valid object. As such, you might find code like this:

      Foo list[] = { somePointer, anotherPointer, NULL };
      bar(list);
      

      instead of

      Foo list[] = { somePointer, anotherPointer };
      bar(sizeof(list)/sizeof(*list), list);
      

      This is why the execvpe() only needs three arguments, two of which pass arrays of user defined length. Since all that's passed to execvpe() are (possibly lots of) strings, this little function actually sports two levels of zero termination: null pointers terminating the string lists, and null characters terminating the strings themselves.

    3. Even when the element type of the array is a more complex struct, it may still be zero terminated. In many cases, one of the struct members is defined to be the one that signals the end of the list. I have seen such function definitions, but I can't unearth a good example of this right now, sorry. Anyway, the calling code would look something like this:

      Foo list[] = {
          { someValue, somePointer },
          { anotherValue, anotherPointer },
          { 0, NULL }
      };
      bar(list);
      

      or even

      Foo list[] = {
          { someValue, somePointer },
          { anotherValue, anotherPointer },
          {}    //C zeros out an object initialized with an empty initializer list.
      };
      bar(list);
      
    0 讨论(0)
提交回复
热议问题