What is malloc doing in this code?

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

    malloc is a function that allocates a chunk of memory on the heap and returns a pointer to it. It's similar to the new operator in many languages. In this case, it's creating a block of memory that can survive for an arbitrary length of time and have an arbitrary size. That in itself is fairly in-depth stuff, which is somewhat difficult to explain and warrants a separate question.

    The num + 1 compensates for the null terminator on the end of strings. Strings often need to know how long they are, and the C tradition is to allocate room for an additional character on the end of the string, which will always be the special character \0. That allows functions that deal with the string to determine the size of the string automatically. For example, if you wanted to do something to every character of a string without knowing how long the string is, you could do something like this:

    const char *ptr = str;
    while (*ptr != '\0') {
        process(*ptr);
        ptr++;
    }
    

提交回复
热议问题