If you wanted to allocate an array of some type, you would normally multiply the number of elements you wanted by the size of that type, because malloc
takes the size of the array in bytes.
However, an array of char
is a special case; you do not need to multiply the number of elements you want by sizeof(char)
, because sizeof(char)
is defined by the Standard to always be 1
, and multiplication by 1 yields the other operand.
The + 1
is to make room for the NUL
terminator. If you want a string of length n
, your array has to be of length n + 1
; n
spaces for the n
characters of the string, and 1
space for the terminator.
By the way, you shouldn't cast the return value of malloc
. It will make your code easier to change in the future.