What is malloc doing in this code?

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

    Malloc in this case is allocating num+1 times sizeof(char) bytes. This is standard practice when you want to allocate an array of elements. The char in sizeof(char) is typically replaced with the type of array being allocated.

    Strictly speaking in this example though the sizeof(char) is not necessary. It's guaranteed to be of size 1 by the C standard and hence just multiplying by 1.

提交回复
热议问题