Lets 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 the loop to initialize each element to NULL necessary or are they automatically NULL from calloc?
All pointers, when they are created, should be initialized to some value, even if it is only zero. A pointer whose value is zero is called a null pointer. Practice safe programming: Initialize your pointers!
You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.
It is necessary only when you expect it to have a default value. As pointers, just like other variables will hold garbage value unless it is initialized.
Declaring and initializing a pointer is very essential as they work with the addresses of the memory directly.In this article, you will learn about the difference between the null pointer and the void pointer.
Yes, the assignment to NULL in the loop is necessary. calloc
initialises to all bits 0. But a null pointer may not be represented like that. It is implementation dependent. Thus the assignment is necessary.
That depends a bit on your system, but in the vast majority of cases it's ok. calloc()
returns you a buffer filled with zeros. However, the null pointer on your machine might not be a bit pattern of 0. On a machine where the null pointer is non-zero, you might end up in trouble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With