The terminating NULL in an array in C

前端 未结 9 1015
走了就别回头了
走了就别回头了 2021-01-21 04:15

I have a simple question.
Why is it necessary to consider the terminating null in an array of chars (or simply a string) and not in an array of integers. So when i want a

相关标签:
9条回答
  • 2021-01-21 04:47

    Actually - you don't have to NUL-terminate your strings if you don't want to! The only problem is you have to re-write all the string libraries because they depend on them. It's just a matter of doing it the way the library expects if you want to use their functionality.

    Just like I have to bring home your daughter at midnight if I wish to date her - just an agreement with the library (or in this case, the father).

    0 讨论(0)
  • 2021-01-21 04:50

    It's not absolutely necessary to have the character array be 21 elements. It's only necessary if you follow the (nearly always assumed) convention that the twenty characters be followed by a null terminator. There is usually no such convention for a terminator in integer and other arrays.

    0 讨论(0)
  • 2021-01-21 04:51

    It is only by convention that C strings end in the ascii nul character. (That's actually something different than NULL.)

    If you like, you can begin your strings with a nul byte, or randomly include nul bytes in the middle of strings. You will then need your own library.

    So the answer is: all arrays must allocate space for all of their elements. Your "20 character string" is simply a 21-character string, including the nul byte.

    0 讨论(0)
提交回复
热议问题