What is malloc doing in this code?

后端 未结 11 974
眼角桃花
眼角桃花 2021-01-01 04:59

Could you explain following code?

str = (char *) malloc (sizeof(char) * (num+1));
  1. What is malloc doing here?
11条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-01 05:07

    This code tries to allocate a chunk of memory that can hold num + 1 values of type char. So if a chat equals one byte and num is 10 it will try to allocate 11 bytes of memory and return a pointer to that memory.

    +1 is likely used because the programmer wanted to store a string (character array) of num characters and needs an extra char to store the terminating '\0' (null) character. In C/C++. chracater strings are, by convention, terminated by a null-character.

提交回复
热议问题