Is null character included while allocating using malloc

后端 未结 4 585
野趣味
野趣味 2020-12-03 12:49

I have been using C for quite sometime, and I have this trivial problem that I want to query about.

Say i want to create a character array that stores upto 1000 cha

4条回答
  •  我在风中等你
    2020-12-03 13:16

    If you need that block for storing null-terminated string then yes, you need to explictly ask malloc() to allocate an extra byte for storing the null-terminator, malloc() will not do it for you otherwise. If you intend to store the string length somewhere else and so you don't need the null terminator you can get away without allocating the extra byte. Of course it's up to you whether you need null-termination for strings, just don't forget that C library string handling functions only work with null-terminated strings.

提交回复
热议问题