Advertisement
alien_fx_fiend

Introductory Guide to Pointers in C

Jun 10th, 2015
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. Introductory guide to Pointers in C
  2.  
  3. 1. Introduction
  4.  
  5. C is a very powerful programming language that are used by many software developers to develop different kinds of software. However, 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. 
  6.  
  7.  
  8. 2. Pointers, Addresses and Variables 
  9.  
  10. A pointer is a variable that holds a memory address.
  11.  
  12. 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:
  13.  
  14. int nVariable = 5; int *pPointer = &nVariable; 
  15.  
  16. The first statement declares a variable "nVariable" of type integer and assigns a value 5 to it.
  17.  
  18. The second statement declares a pointer variable that holds the address of an integer, and assigns the address of the variable "nVariable" to it.
  19.  
  20. 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".
  21.  
  22.  
  23. 3. Indirection
  24.  
  25. The term "Indirection" refers to the method of accessing the value at the address held by a pointer.
  26.  
  27. The indirection operator (*) is also called the dereference operator. The following code snippets in C++ shall illustrate this method:
  28.  
  29. int nVariable = 5; int *pPointer = &nVariable; printf("The output is %d", *pPointer);
  30.  
  31. 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".
  32.  
  33.  
  34. 4. Conclusion
  35.  
  36.  
  37. 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.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement