Friday, November 13, 2009

C/C++ pointers 101

If you're gonna be using pointers you should know what they are and why they are useful instead of just learning the syntax. So here's a brief little introduction followed by how to use them.

What are pointers

Pointers are very useful. Why? Because instead of passing large data structures (class, struct, arrays) into functions you simply pass in the address. The pointer's size is very small, it's just the size of the integer representation of the memory of it's pointing to. So using pointers effectively will make your code more efficient.

Why do only C/C++ use pointers?
They don't. Higher level languages hide the fact that they are using pointers. For example in Java, it's completely object oriented, which means every object is really a reference. The reason they abstract the idea of a pointer away from you is because it's a difficult concept to try to learn.

How to use pointers (using simple examples)
int a = 3; //first you create something to be pointed to
int *ptr; //then you create the pointer, using the * syntax
ptr = &a; //assign the pointer to the address of (&) of a

let's say a's address in memory is 0x123 for the following examples:

cout << *ptr << "=" << 3="3" 0x123="0x123" style="font-style: italic;">Pointers as arrays
function caller()
int *a;
for(int i = 0; i < 5; i++)
(a+ i) = &i; //set a[i] to i
printArray(a, 5);


function printArray(int *a, int size)
for(int j = 0; j < size; j++)
cout << a[i] << endl;

printArray will print out

Now you know the basic essentials of pointers. Now apply that to larger objects (like structs) and it works the same way.

No comments:

Post a Comment