Introductory guide to Pointers in C

Feb 26
16:08

2009

Dennis Chang

Dennis Chang

  • Share this article on Facebook
  • Share this article on Twitter
  • Share this article on Linkedin

Much of the difficulties in learning C comes from the confusion over the concept of pointers. This article aims to provide a simple guide to understanding the concept of pointers, addresses and variables in C.

mediaimage

1.      Introduction

C is a very powerful programming language that are used by many software developers to develop different kinds of software. However,Introductory guide to Pointers in C Articles for a beginner, C is a rather difficult language to grasp. Much of the difficulties in learning C comes from the confusion over the concept of pointers. In this article, I shall explain the concept of pointers with the help of some code snippets.

2.      Pointers, Addresses and Variables

A pointer is a variable that holds a memory address.

It is important to differentiate between a pointer, the address that the pointer holds, and the value at the address held by the pointer. This is the source of much of the confusion about pointers. We will illustrate this in the following code snippets:

int nVariable = 5;         

int *pPointer = &nVariable;     

The first statement declares a variable “nVariable” of type integer and assigns a value 5 to it.

The second statement declares a pointer variable that holds the address of an integer, and assigns the address of the variable “nVariable” to it.

So let just imagine the memory is a set of lockers. Each of these lockers has a locker number assigned to it for identification purposes. The first statement will do something like reserving the locker number “1234”, and put the value “5” into this locker. The second statement will do something like reserving the locker number “4321”, and then put the value “1234” into the locker. So the locker number “4321” is actually storing the locker number of the locker that stores the value “5”.

3.      Indirection

The term “Indirection” refers to the method of accessing the value at the address held by a pointer.

The indirection operator (*) is also called the dereference operator. The following code snippets in C++ shall illustrate this method:

int nVariable = 5;

            int *pPointer = &nVariable;

            printf(“The output is %d”, *pPointer);

The output of the code snippets will be the number “5”. Remember that “pPointer” is a pointer variable that holds the address of the variable “nVariable”. Notice that we use “*pPointer” to assess the value hold by the variable “nVariable”, and this is what we call “Indirection”.

4.      Conclusion

This article aims to provide a simple guide to understanding the concept of pointers, addresses and variables in C. Readers are assumed to have some basic knowledge in C.