Pointers, and Pointer Arithmetic

CS 301 Lecture, Dr. Lawlor

So, pointers.  A pointer is "a memory address".  What the heck does that mean?  Well, "Memory" means your machine's RAM.  It stores an array of bytes.

A memory address is the number of a byte in RAM, just like an array index into your machine's big array of bytes.  The lowest address is 0, which is the special invalid address "NULL".  The highest address on a 32-bit machine is 0xffFFffFF (capitalization in hex is optional, like 0xBeefF00D).

That is, a pointer is just a number.  A number of bytes.  The CPU uses this number to look up the corresponding data stored in memory.

Pointer Arithmetic

You can change the number.  This is called "pointer arithmetic", and it's really common in C:
char *str="Woa!  That's a *string?";
std::cout<<"The string is '"<<str<<"'\n";
return 0;

(executable NetRun link)

This prints out:
The string is 'a!  That's a *string?'
A "char *" string points to the first character of the string, and like all arrays, the next character is in the next byte of memory.

The deal in this program is that we've advanced the pointer over the "W" and "o" characters by adding two to ptr.  Try it!  You can move the pointer forwards and backwards over the characters of the string.  You can even move the pointer off the end of the string (in either direction), in which case it'll print out garbage or (if you move far enough) reach invalid memory and crash.

Pointers In Assembly

mov eax, my_string  ; eax now points to my_string
add eax,2 ; Advance over the first two bytes of the string

push eax ; printf(eax);
extern printf
call printf
pop eax


db "This we a string",0xA,0 ; "db" means add bytes. 0xA is newline. 0 ends.

(executable NetRun link)

Notice that "eax" can hold an int, or a pointer.   The assembler doesn't care which. 

In assembly, "pointer arithmetic" is just the same as normal arithmetic.