What is malloc doing in this code?

后端 未结 11 981
眼角桃花
眼角桃花 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:08

    malloc allocates memory from the heap and returns a pointer to it. It's useful when you don't know how much memory you are going to need at compile time.

    As for why (num+1), it really depends on what the code is doing... perhaps num is the number of characters in the string, and the +1 is for the NUL terminator byte at the end. I don't know what the sizeof(char) would be for in that case, though.

提交回复
热议问题