Is null character included while allocating using malloc

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

    malloc and family allocate memory in chunks of bytes. So if you do malloc(1000) you get 1000 bytes. malloc will not care if you allocated those 1000 bytes to hold a string or any other data type.

    Since strings in C consist of one byte per character and ideally have to be null terminated you need to make sure you have enough memory to hold that. So the answer is: Yes, you need to allocate 1001 bytes if you wish to hold a string of 1000 characters plus null terminator.

    Advanced tip: Also keep in mind that depending on how you use it you may or may not need to null terminate a string.

    If you for instance know the exact length of your string you can specify that when using it with printf

    printf("%*s", length, string);
    

    will print exactly length characters from the buffer pointed at string.

提交回复
热议问题