2.5. Pointers


Pointers and pointer types

A pointer is a memory address.

In Java, every variable whose type is a class contains a pointer. Since everything is a pointer, there is no need to see pointers explicitly.

In C, pointers are explicit. A variable of type T* contains the address of a chunk of memory that holds an object of type T.

Examples of pointer types are int*, char* and char** (the type of a pointer to a variable of type char*).


Creating pointer variables

Declaration

  int* r;
creates an automatic variable r that can hold a pointer to a variable of type int.

Be careful. If you want to create two or more pointer variables, you are required to write a * in front of each one. So

  int *r, *s;
creates variables r and s, of type int*. But
  int *r, s;
creates variable r of type int* and s of type int.


Getting a pointer to a variable

If x is a variable then &x is the address where x is stored. Be careful with this: addresses in the run-time stack are lost to you when the stack frame containing them is destroyed.


Indirect addressing

If variable p has type T* then *p is the thing, of type T, to which p points. For example,

  int x;
  int* p = &x;
  *p = 25;
stores 25 into x.


The null pointer

The null pointer is called NULL. It is not really part of C; it is defined in header files stdio.h and stddef.h.


Call by pointer

Pass a pointer to a function to allow the function to use the memory pointed to by that pointer. The function can read or write that memory.


Const pointers

A pointer of type const T* can only be used to read memory, not to write that memory.