UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

Chapter 5.  Pointers in C

Pointers are one of the most powerful features of the C programming language, but at the same time, one of the the most complex to master. Pointers allow to manipulate the computer memory very efficiently. Two concepts are fundamental to understand how pointers work:

  1. The size of all variables and its position in memory.

  2. Every data is stored in memory starting at a certain address. This address may be obtained and manipulated also as a regular data.

Pointers in C are also one of the most frequent source of errors. The low level manipulation of the memory, together with few checks that the compiler enforces, makes designing programs with pointers a task that requires great meticulousness matched by an equal amount of patience. Program efficiently with pointers is a skill acquired after writing many lines of code, and requires a sustained practice.

We recommend that you read this document with your development environment ready to try small code fragments and programs. You must compile and execute them to check that they behave as expected.

5.1.  Every data has an address in memory

Every data is stored from certain memory address and using as many bytes as needed. For example, let us consider the following data definition and its corresponding memory representation starting at position 100:

Assuming that int and float occupy 4 bytes, and char occupies 1 byte, if d1 is stored starting in address 100, then its n1 field has that same address, field n2 is stored in position 104 and field st is stored starting at position 108.