In this article, we’re going to introduce a new, special data type which is crucial for programming in C (and practically any other language).
This type is called a pointer, and it is specific, since its value is an address of some other variable. It is said that a pointer references a location in memory. This location in memory i.e. some variable, can be accessed through the pointer that’s referencing it.
A pointer in your code is declared like this:
int* pointerToInt; /* or this: int *pointerToInt; */
Note that this notation doesn’t mean that a pointer is an integer or character. It means that the pointer is referencing a variable of type int and char, respectively. The pointer itself is always a 4 or 8-byte variable (depending on the size of the system’s address bus: on a 32-bit machine there is a maximum of 232 usable addresses, hence the size of a pointer will be 32 bits, and the same goes for 64-bit machines).
int a = 5;
int* ptr = &a;
In this example, we’ve assigned the address of the variable a to the pointer ptr, by using the address operator &: &a means “address of a.”
Obtaining the value stored in the location which the pointer is referencing is called dereferencing that pointer. Again, the asterisk sign is used:
*ptr = 8;
Effectively, we have assigned the value 8 to our variable a.
Pointers to data significantly improve performance for repetitive operations such as traversing strings, lookup tables, and tree structures. They are at the very core of programming, allowing dynamic memory allocation and more complex data structures.
However, they demand concentration and a certain degree of wisdom. They can easily diminish your program’s performance and are a common source of failure, because they can cause a special kind of runtime error (the kind that your compiler cannot recognize). This runtime error, called segmentation fault, occurs when you try to access a part of the memory which you don’t have the right to access.
In our next programming article, we’ll discuss a new way to use arrays—dynamic memory allocation—which allows you to declare arrays without knowing from the beginning what the size of the array will be. We will also mention common data structures such as stack and queue, which use pointers to link elements and are widely used in various algorithms.