Why do strings in C need to be null terminated?

前端 未结 9 1190
青春惊慌失措
青春惊慌失措 2020-11-29 04:53

Just wondering why this is the case. I\'m eager to know more about low level languages, and I\'m only into the basics of C and this is already confusing me.

Do langu

9条回答
  •  情书的邮戳
    2020-11-29 05:25

    C strings are arrays of chars, and a C array is just a pointer to a memory location, which is the start location of the array. But also the length (or end) of the array must be expressed somehow; in case of strings, a null termination is used. Another alternative would be to somehow carry the length of the string alongside with the memory pointer, or to put the length in the first array location, or whatever. It's just a matter of convention.

    Higher level languages like Java or PHP store the size information with the array automatically & transparently, so the user needn't worry about them.

提交回复
热议问题