Pointer

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

Introduction

A pointer "points" to another location in memory.

Overview

The way a computer works, data is laid out across memory. If you want to find something, you have to obtain the pointer to the data you want, which is really the memory address of the data.

In most languages, this is handled for you. The variables and data types keep track of the memory addresses under the covers so you never have to worry about where data really is. It is abstracted for you.

In some languages, particular C/C++ and asm, you have to do a lot of the work yourself if you want to work with data outside of the stack.

Note that you may have pointers to pointers, or even pointers to pointers to pointers to pointers. In other words, variables that store the address of a section of memory that stores the address of a section of memory that stores the address of...

Pointer Operations

Obtain a Pointer

You should always get a pointer to the newly allocated memory segment when you allocate memory.

char *ptr = new char[27];

You may obtain the pointer to a variable with the '&' (address-of) operator in C/C++.

char c = 'a';
char *ptr = &c;

Assign a Pointer

You can assign a pointer to another pointer, as long as the types match. If not, then you need to do some typecasting.

Extract Data

To obtain the data that the pointer is pointing to, use the '*' (contents-of) operator in C/C++.

char c = *(char *)ptr;

Notice the pattern:

X a = *(X*)b;

So:

char *c = *(char **)ptr;

Pointer Math

If a pointer is pointing to the start of a vector, you can add or subtract integers from the pointer to move to that item in the vector.

ptr+0 => the head or first item of the vector
ptr+1 => the second item of the vector
ptr+n => the (n+1)th item of the vector

In C, the square braces give you a nifty shortcut that combines extraction with pointer math.

ptr[n] === *(ptr+n)

Derefernced member

Another shortcut is the -> operator in C/C++.

ptr->member === (*ptr).member