Using the Wrong Address Operator to Initialize a Pointer

If you're still learning about pointers, it's easy to forget which address operator to use when initializing a pointer variable. For example, you might want to create a pointer to a simple int variable:

int val = 25;

int *ptr;

ptr = val; /* Error! */

The code above doesn't initialize ptr correctly. Instead of assigning to ptr the address of val, the statement

ptr = val;

tries to assign ptr the contents of val, causing an error message:

warning C4047: '=' : different levels of indirection

Because val is an int variable, its contents can't form a meaningful address for ptr. You must use the address-of operator to initialize ptr:

ptr = &val;

Here's another pointer initialization error:

int val = 25;

int *ptr;

*ptr = &val; /* Error! */

The last line doesn't initialize ptr to point to the variable val. The expression to the left of the equal sign, *ptr, stands for the object ptr points to. Instead of assigning ptr the address of val, the line tries to assign the address of val to the place where ptr points. Because ptr has never been initialized, the assignment triggers a run-time error:

run-time error R6001

-null pointer assignment

Here is the correct way to initialize this pointer:

ptr = &val;