Skip to content

Pointers and Functions in C Programming Language

Objective

At the end of this chapter, you should be able to read, write, compile and run simple C programs with the following features:

  • Pointers with additional understanding on:
    • Pointer arithmetics
  • Functions with additional understanding on:
    • Scoping rule
    • Pass-by-value

Preliminary

Pointers

Pointer

Recap that every variables in C has four attributes: name, type and address. A pointer is --in essence-- a variable that stores the address of another variable. In other words, the value of a pointer is an address to another variable.

You may not realise it, but you have been using pointers in your code before. However, the way it is used is hidden from you. Furthermore, you cannot perform arithmetic operations on the pointers directly.

  • JavaScript: Objects ({a: 2}) and arrays ([1, 2, 3]) are actually pointers.
  • Python: Everything in Python are actually an object and hence, pointers. However, immutable objects behave like they are primitive data type.

In C, pointers are made explicit. In particular, C allows for:

  • Direct manipulation of memory contents.
  • Arithmetic operations on pointer.

Pointer is one of the reason why C is considered to be at the lower-level of the high-level programming languages1.

Functions

Functions are named abstraction of a computation. In other words, we can perform a computation by calling its name. We will discuss how to call functions and how to define our own functions in C. More importantly, we will show how functions and pointers interact in unexpected (but reasonable) ways.

Quick Recap on Variable

A variable occupies some space in the computer memory. Hence, it has an address.

Variable
1
2
int /* data type */ a; /* name */
a = 123; /* value: may only be integer */

Variable in Memory

Look at the code above, where is the address of variable a? We can represent the variable a with the box on the right. Now, what is the address?

We usually do not need to know the address of the variable. We simply refers to the variable by its name. Nevertheless, the system keeps track of the variable's address.


  1. Another reason is that C has a set of bit manipulation operators that allow for efficient bitwise operations.