If string arrays are null terminated in C, why are arrays of other data types not null terminated?

前端 未结 4 1321
醉酒成梦
醉酒成梦 2021-01-20 06:14

Strings, or arrays of characters in C must be null terminated to know where they end. Why does the same rule not apply to arrays of other types? eg. How does the computer kn

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-20 07:07

    Arrays of characters do not have to be nul-terminated.

    char foo[3]="foo"; //not nul-terminated
    char bar[]={'b','a','r'}; //not nul-terminated
    

    It's just that string literals are nul-terminated arrays, and that C makes it really easy to make nul-terminated arrays by using string literals as initializers:

     char baz[]="baz"; //nul-terminated because "baz" is
    

    Why C does so is a choice the designer(s) made because using a terminator seemed more convenient to them than maintaining character counts next the character array.

    But nothing in C forces this preference on you.

提交回复
热议问题