Pointers

In Progress

Pointers

You can think of pointers as the address of your house. The pointers are the variables that store addresses of the memory locations. Pointers are most often used in C language as compared to other programming languages.

Consider the following variable declaration;

The above line of code;

  1. Reserves a space in the memory to hold the integer value.
  2. Associate the name “a” with that space.
  3. Store the value “3” at that location.

Now, we can show this diagrammatically as;

It is obvious that computer has selected the location of this variable itself. The location number may change each time you compile and run the computer. The important thing to note is that the location is always a number.

Now look at the following program;

Observe;

  • The &(address of) operator being used in printf statement.
  • %u, format specifier for unsigned integer has been used, because we are printing an address and there no need to associate sign.

The output of this program will be;

Address of i = 65524

Value of i = 3

Another pointer operator in C is “*”. It is called “value at address” operator. It gives the value stored at particular address. It is also called “indirection” operator.

Now look at the program below;

Here in this program another printf statement has been added to explain the use of * operator;

The output of this program will be;

Address of i = 65524

Value of i = 3

Value of i = 3

Note that printing the value of *(&i) is same as printing the value of i.

We can read it as the value at the address (address of i); when translated it will eventually give you the value of i

The expression &i is telling the address of i, we can assign a this value to a variable as;

j = &i;

Now, j is not an ordinary variable lie any other integer variable. It is a variable containing the address of another variable. But again it’s a variable so it also must be assigned a space in memory.

Here, you can see that i’s value is j, and j’s value is i’s address.

But we can’t use j in any program without declaring variable.

j will be declared as;

int *j;

This declaration tells the compiler that j will be used to hold the address of an integer variable. In other words j will point an integer.

This is how you can point variables using the operators & and *.