Could you explain following code?
str = (char *) malloc (sizeof(char) * (num+1));
malloc
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.