Is null character included while allocating using malloc

后端 未结 4 572
野趣味
野趣味 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:08

    It's up to you to provide the null-terminating character.

    malloc allocates memory for you but it doesn't set it to anything.

    If you strcpy to the allocated memory then you will have a null-terminator provided for you.

    Alternatively, use calloc as it will set all elements to 0, which is in effect the null-terminator. Then if you do, say, memcpy, you wouldn't have to worry about terminating the string properly.

提交回复
热议问题