Initializing a Pointer Variable

The next step in the POINTER.C program is to initialize the pointer variable ptr, making it point to some meaningful address in memory:

ptr = &val;

The “address-of operator” (&) gives the address of the name it precedes. So in plain English the above statement says, “assign the address of val to ptr.”

After its initialization, the variable ptr points to val in the sense that it contains the address where val is stored.

The output from POINTER.C shows that ptr contains the address of val. First it prints the address of val using the address-of operator to directly obtain the variable's address,

&val = 5308

then it prints the contents of ptr:

ptr = 5308

The two values are identical. Figure 8.2 shows the relationship of val and ptr at this stage in the POINTER.C program.

Initialization is especially important for pointers because, as noted earlier, they have the potential to point anywhere in memory. If you forget to initialize it, or make it point to the wrong place, a pointer can wreak havoc with your program or even the operating system itself.

Summary: The target of a pointer must be present in memory at run time.

The pointer in POINTER.C points to a simple int variable. As a general rule, pointers can point to any data object that is present in memory at run time. This category mainly includes objects for which the program allocates (sets aside) memory. Memory can be allocated implicitly, by defining a variable or function, or explicitly, by calling a memory-allocating library function such as malloc.

A pointer can't point to program elements such as expressions or register variables, which aren't present in addressable memory.

POINTER.C initializes the pointer ptr by assigning it an address constant (the address of val, obtained with the address-of operator). You can also assign the value of one pointer to another, as shown here:

ptr = ptr1;

If ptr and ptr1 are both pointers, this statement assigns the address contained in ptr1 to ptr.