Search code examples
cpointersalloc

is it necessary to call pointer = NULL when initializing?


when I create a pointer to certain struct, do I have to set it to NULL, then alloc it then use it? and why?


Solution

  • No, there is no requirement (as far as the language is concerned) to initialize a pointer variable to anything when declaring it. Thus

    T* ptr;
    

    is a valid declaration that introduces a variable named ptr with an indeterminate value. You can even use the variable in certain ways without first allocating anything or setting it to any specific value:

    func(&ptr);