Search code examples
cpointersaddressof

difference between setting up pointer with address-of operator


I wondered what is the big difference between setting up C pointers in this way:

int int_var = 5;
int *int_ptr = &int_var;

And this way:

int int_var = 5;
int *int_ptr = int_var;

Since in both cases the result of *int_ptr will be 5, no?


Solution

  • No, only in the first case. The second case will cause undefined behavior when you'll try to deference the pointer. Use the first case.

    Some explanation:

    int int_var = 5;
    int *int_ptr = &int_var; // here int_ptr will hold the address of var
    

    Whereas

    int int_var = 5;
    int *int_ptr = int_var; // here int_ptr will hold the address 5.