The (structName **)
before malloc
is a mistake. It was required in the 1970s, but has been a mistake since 1989. Many people didn't update their learning materials since 1989 ;-)
At best it is redundant text (and redundant text should usually be avoided as it makes the important text harder to read), and at worst it can hide an error. For further reading on that topic see this thread.
Regarding the second part, 0 * sizeof(structName *)
. This is of course 0
and you may well ask why the person didn't just write 0
.
The reason is that the person is conforming to a particular style for use of malloc. Conforming to a pattern is a way of minimizing errors. If you read this site regularly you'll know that incorrect use of malloc is one of the most common sources of bugs that people have trouble tracking down. The pattern being used is:
T *ptr = (T *) malloc( number_of_elements * sizeof(T) );
which allocates an array of a certain number of elements of type T
. This is legal even if the number is 0
(but not legal for negative numbers); in which case it may either return a null pointer, or a non-null pointer. In either case, you can't try and access any array elements , of course.
This pattern is common, but as mentioned in the linked thread, has problems and since 1989 there has been a better option.
NB. Consider using calloc
to allocate memory. It's slightly clearer in that the two numbers are separated by a comma instead of by a multiplication operator, and on some operating systems (e.g. Linux) it can perform faster than malloc
.