A pointer is a variable that contains the address of a variable.
Let’s look at a simplified picture of how memory is organised. A typical machine has an array of consecutively numbered or addressed memory cells that may be manipulated individually or in contiguous groups. Any byte can be a char, a pair of one-byte cells can be treated as a short integer, and four adjacent bytes form a long. A pointer is a group of cells (often two or four) that can hold an address. So, if c is a char and p is a pointer that points to it, we could represent the situation like this:
We can get the address of an object using the unary operator &.
p = &c;
assigns the address of variable c to the pointer variable p. p is said to “point to” c. The & operator can only be applied to objects in memory: variables and array elements. It can not be applied to expressions, constants or register variables.
The unary operator * is the indirection or dereferencing operator. It can be applied to a pointer to access the value it points to. Let’s look at the following example:
int i = 10; float f = 2.3f; char arr[] = "hello"; int *pi; /* pi is a pointer to int */ float *pf; /* pf is a pointer to float */ char *pc; /* pc is a pointer to char */ pi = &i; /* pi now points to i */ pf = &f; /* pf now points to f */ pc = &arr[1]; /* pc now points to arr[1] */ printf("%d is same as %dn", i, *pi); printf("%f is same as %fn", f, *pf); printf("%c is same as %cn", arr[1], *pc);
We declare three pointers in the above example. Let’s look at one of them:
int *pi;
declares a variable pi which is a pointer to an int. Just like any other automatic int variable, by default pi here has some garbage value. So, we need to assign it an address of some int variable like this:
pi = &i;
Now, pi points to i, we could use dereferencing operator * to get the object pointed to by pi. So, *pi would give the same value as i and can be used to modify i like this:
*pi = *pi + 1;
or
++*pi;
or
(*pi)++;
The parenthesis are necessary in the last example as unary operators like ++ and * associate from right to left (Check the order of evaluation table).
We could also assign a pointer variables with the values of another pointer. For example:
int *p = pi;
copies the value of pi to p. Thus, p points to the variable i as well (same as pi).