Pregunta

Generally what I have to do? I should always initialize ptr?

char *ptr;

ptr = malloc (10);

OR

char *ptr = NULL ;

ptr = malloc (10);

And in a function?

void func(char **ptr)
{
    *ptr = malloc(10);
}

int main()
{
    char *ptr; /* OR char *ptr = NULL; ? */

    func(&ptr);

    return 0;
}
¿Fue útil?

Solución

Initialize before using it.

Note, Assigning is also a initialization.

So,

char *ptr;

ptr = malloc (10);

is OK.

But in case of

void func(char **ptr)
{
    *ptr = malloc(10);
}

int main()
{
    char *ptr; /* OR char *ptr = NULL; ? */

    func(&ptr);

   return 0;
}

You should initialize as you may not know what the function will do with the pointer.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top