What are pointers

12 pointers

This chapter deals with perhaps the most important and versatile topic in the C programming language: the pointers. However, this is a topic that is often not understood straight away. But once the pointer arithmetic is clear, the hurdles of the advanced chapters no longer seem so high. So: If the subject of pointers is no longer a problem, then the C programming language is no longer a problem either.

Basically, however, pointers are not as complicated as they are often represented. In principle, pointers are nothing more than normal variables that contain addresses of a specific memory area instead of data objects such as numbers, characters or structures.

What can you do with pointers to addresses? Here is a brief overview of the areas of application of pointers:

  • Memory areas can be reserved, managed and deleted again dynamically.
  • You can use pointers to transfer data objects directly (call-by-reference) to functions.
  • Pointers can be used to pass functions as arguments to other functions.
  • Recursive data structures such as lists and trees can almost only be created with pointers.
  • A typeless pointer (void *) can be defined, with which data objects of any type can be processed.

On the next few pages I will first explain the basics of pointers (which are often also called pointers). The aforementioned points will then be discussed in the course of the book. I recommend that you devote plenty of time to this chapter. It is definitely the foundation for the progress of the book and your career as a C programmer.


12.1 Declare pointers

The declaration of a pointer has the following syntax:

Data type * pointer variable;

The data type of the pointer must be of the same data type as the one to which it points (referenced).


Note

When I speak of "pointing to something" in the following, of course I mean that a specific memory area (an address in the main memory) is referenced.


The asterisk in front of pointer variable indicates the data type as a pointer. In technical jargon, this operator is called the indirection operator. The position for the asterisk is between the data type and the pointer name. Example:

int * pointer1; int * pointer2; char * pointer3; char * pointer4; float * pointer5;

Here you can see two different spellings, both of which are correct; however, the following has become commonplace:

int * pointer1; int * pointer2; int * pointer3;

With this notation, the mistake made becomes clearer:

Only one pointer was declared here, which can be seen quite quickly. With the following notation, this error is no longer so clearly recognizable:

Here one could wrongly assume that two pointers have been declared. So it is best to use the usual notation. This can save you a few problems.



your opinion

How did you like the Openbook? We always look forward to your feedback. Please send us your feedback as an e-mail to [email protected]