Ok, here is the John Shaw quick guide to pointers.
A pointer is a type that holds a memory address which contains data of the pointers type.
So if ptr is an int pointer and ptr = 0xF003 then there is an int at memory address 0xF003.
The operations are as follows:
*ptrvar = the value at the memory address the pointer is set to.
&nonptrvar = the memory address of a non pointer.
So if I have a regular int x and a an int pointer iptr and I want iptr to point to x I would say iptr = &x.
Pointers are particular nice for pointing for dynamic groups of data (aka dynamic arrays, matrices). Check out the malloc, realloc, and free functions to see how you allocate dynamic memory.
Operations here:
int *ptr = malloc (sizeof(int) * 10); //allocates a dynamic array of 10 ints pointed to by ptr.
ptr = realloc (ptr,sizeof(int) * 20); //reallocates the array to that of 20 ints
ptr[3] = 10; //sets the 4th element of the array to 10 (c arrays start at 0!)
*(ptr+3) = //same as the line above.
free(ptr); // Frees up the memory and points ptr to NULL.
Some good rules to follow:
- Initialize pointers to NULL. If you are going to be dynamically allocating the memory for a pointer later then initialize it to NULL now. This way you don't have a pointer pointing to something random that can cause weird bugs if you accidentally use it pointing to that random location.
- Always always always check to make sure a pointer doesn't equal NULL before you use it. If you follow this rule and the rule above you will save yourself a lot of grief.
- Be careful when going through dynamic arrays. Make sure you keep good track of the size. All too often you see cases where people try and load a spot in the array they haven't allocated memory for and instead of causing the program to exit it causes seemingly unexplainable weirdness in your programs operation. This also leads to the famous buffer overflows in programs that plague security.
This is pretty basic but I hope it helps you out.