Html/Javascript widget

Sunday, 4 June 2017

Quick Introduction to Pointers

A pointer is a variable containing the address of another variable.

Take for instance the declared variable variable1 in C:

int Variable1;
, store the number ‘96’ in it with

and print it out with


Instead of referring to this data store by name (in this instance, variable1), it can be done so by its computer memory address, which can be in a pointer, which is another variable in C. Using the operator '&' means "to take the adress of" while the operator * means to give the pointer whatever is in said address. A pointer to the code above could look like this:


This stores the address of variable1 in the variable Pointer1.

To take the value, we would use *:


which would have the same effect as


or print it out with


So far it should be clear that for pointers we need to use & to take the memory address of a variable while * takes hold of its value.

A pointer is created as below:

int *Pointer1;

The reason that the symbol * comes after the type when delcaring pointers is because it's necessary to specify the type that the pointer has to point to. An int *pointer points only to integer. A char *var points only to chars and so on.

Pointers are necessary for dynamic memory location, data structures and efficient handling of large amounts of data. Without pointers, you'd have to allocate all the program data globally or in functions or the equivalent, resulting in a lot of waste for variables that are not being used but are still taking up memory space.

No comments:

Post a Comment