Is this pointer initialization necessary?

Say I have the following:

CHARLINK * _init_link(CHARLINK **link) { short i; (*link)->cl = (CHARLINK **) calloc(NUM_CHARS, sizeof(CHARLINK *)); for (i = 0; i < NUM_CHARS; i++) (*link)->cl[i] = NULL; return (*link); } 

Is a loop required to initialize each element to NULL or are they automatically NULL from calloc?

+6
c initialization malloc
source share
3 answers

Yes, you need to assign NULL in the loop. calloc initializes all bits of 0. But a null pointer may not be represented this way. It depends on the implementation. Therefore, an appointment is necessary.

+13
source share

It depends a little on your system, but in the vast majority of cases, this is normal. calloc() returns you a buffer filled with zeros. However, the null pointer on your computer may not be the bit pattern 0. On a machine where the null pointer is not zero, you may run into a problem.

+7
source share

No, calloc initializes its buffers to 0.

+3
source share

All Articles