Is it necessary to call = NULL during initialization?

when I create a pointer to a specific structure, do I need to set it to NULL and then select and then use? and why?

+5
source share
5 answers

No, there is no requirement (in terms of language) to initialize a pointer variable to everything when you declare it. In this way,

T* ptr;

is a valid declaration that introduces a variable with a name ptrwith an undefined value. You can even use a variable in certain ways without highlighting anything or setting it to any specific value:

func(&ptr);
+8
source

, NULL, , , , ().

, , NULL .

NULL , .

+6

, , . C

T * ptr = malloc(sizeof *ptr);

, . , ( ) , .

, , . " 0 " , . C , .

- . , , . , , . .

+1

, , . , ( ).

0
source

You do not need to initialize a NULL value. If you intend to highlight it immediately, you can skip it.

In may be useful for error handling, as in the following example. In this case, the gap to the end after pplacement would be left quninitialized.

int func(void)
{
    char *p;
    char *q;

    p = malloc(100);
    if (!p)
        goto end;

    q = malloc(100);
    if (!q)
        goto end;

    /* Do something */

end:
    free(p);
    free(q);

    return 0;
}

In addition, and this is my personal taste, always highlight structures using calloc. Lines can be selected uninitialized withmalloc

0
source

All Articles