Search code examples
cpointersinitialization

Comparing two ways of initializing an int pointer


Suppose I have a pointer

int *x;

Then I need to let the pointer point to an int of value, say 42.

Should I do this:

   *x = 42;

or this:

  int y = 42;
  x = &y;

? What is the usual practice?


Solution

  • After this declaration

    int *x;
    

    the pointer x either is equal to NULL (if it is declared outside any function) or has an indeterminate value. So dereferencing the pointer like

    *x = 42;
    

    invokes undefined behavior.

    You can write either

    int y = 42;
    x = &y;
    

    or

    x = malloc( sizeof( int ) );
    *x = 42;