Could you explain following code?
str = (char *) malloc (sizeof(char) * (num+1));
malloc
doing here? Malloc allocates memory, in this case for the string str of length num. (char *) is the type for str sizeof(char) is the number of bytes required for each character. The +1 is for the trailing null character in the string, normally zero.
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.
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.
malloc allocates memory.
num+1 as num is the number of characters in the string and +1 for the null terminator
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++;
}
malloc allocates an array of char (in this case) on the heap.
array will be num+1 long, but the longest string it can possibly hold is 'num' long, because string in C need a ending null-byte.