CCPROG1_pointers
Pointers
original file
Pointers
A pointer in a programming language is actually an address in memory (Hanly & Koffman, 2012). Since this address actually “points” to another address in memory, it is referred to as a pointer.
- We recall that the computer’s memory consists of contiguous locations or spaces which can contain data. Each location or space in memory is referenced (accessed) via its physical address. However, it would be difficult for programmers to remember the exact physical address of each variable in a program. Hence, we employ variable names as aliases. Consider the declaration below:
This means that the name nHeight refers to an integer variable that resides at some location in memory. This memory location has a certain physical address, and it contains the value 100. We can imagine that the memory location looks like this:

- The example illustrates a memory location referred to as nHeight which contains the value 100 and has an address of 200003. In a real program, the actual address of nHeight may be obtained using the ampersand (&) operator.
scanf("%d", &nHeight);
printf("%d\n", nHeight);
printf("%p\n", &nHeight);
- The first statement shows that we need to pass the address of nHeight to scanf() so that it can store the user’s input value into nHeight. The second statement would display the value (contents) of nHeight, while the third statement would display the integer equivalent of the physical address of nHeight (note that we use %p to display the values of a pointer or addresses and these can change every execution of the program).
why do we need to use the physical address?
case:
#include <stdio.h>
void swap(int a, int b)
{ int nTemp;
nTemp = a;
a = b;
b = nTemp;
printf("a = %d, b = %d\n", a, b);
}
int main()
{ int num1, num2;
num1 = 10;
num2 = 20;
swap(num1,num2);
printf("num1 = %d, num2 = %d\n", num1, num2);
return 0;
}
- Initially, we wanted the function swap to exchange the values of num1 and num2, and it actually did for a and b. However, swapping a and b did not affect the values of num1 and num2. Why? It’s simply because num1 and num2 were passed by value to swap(). Let’s trace what happens in memory.

- When parameter num1 is passed by value to swap, only its value is copied to a. When a is modified within swap(), num1 is unaffected, since a is a variable that is different from that of num1. This applies to num2 and b, as well.