+ 1

When declaring a pointer to a variable, do we need to initialize to NULL all the time? Why?

When declaring a pointer to a variable, do we need to initialize to NULL all the time? Why?

30th Dec 2018, 8:46 AM
Konybud
Konybud - avatar
1 Réponse
+ 1
It should be set to something before being used. Initializing when created​ is good practice as it means it is set to something and not an invalid pointer​. It doesn't​have to be initialized​ to null, it could be set to the beginning of an array, depends on what you are doing. If it's a pointer that may or may not hold the address of some dynamically allocated memory later in the program, it is a good idea to initialize to null; then you can test if the memory has been allocated at any point in the program.
30th Dec 2018, 10:12 AM
Jared Bird
Jared Bird - avatar