Pointers
C provides an extremely nice way to access memory via pointer variables. The declaration looks like the following
void *var;
The asterisk before the variable denotes that it’s a pointer variable. A pointer variable stores address of some memory location, typically a variable or a newly allocated memory area.
We know how to declare arrays, let’s take a look at how we can use pointers to traverse the array. We’ll be using a character array and a pointer to a character to traverse the array.
int main() {
char str[] = "Hello World";
char *str2 = str;
while (*str2 != '\0')
printf("%c", *str2++);
return 0;
}
In the above code, we’ve created a character array and then assigned a pointer to it’s base address. The while condition checks the value at the address contained in pointer variable for being null.
Pointers and References
C++ allows us to have references which work mostly like pointers however there’s a very basic and subtle difference. Pointers are first class variables that is they have their own memory location where an address can be stored, while references don’t have their own memory location.
Thus references can’t be uninitialised pointers can be since they are first class variables. This is shown in the table below
Generic Pointers
A pointer always points to some type at a location. However sometimes it’s necessary to write code where the pointer variable required is generic, i.e any type. This is achieved by creating a void pointer.
Sizeof a pointer variable
The pointer variable is always fixed in size and it’s size is machine’s word size. The machine’s word size is denoted by the data type long. This fact is very important since it helps us creating data types that references themselves. For example, while the following piece of code is correct
struct linked_list { struct linked_list *next; void *data; };
struct linked_list { struct linked_list next; void *data; };
Pointer Arithmetic
Pointers like other variables can be used for some arithmetic operations however not all arithmetic operations are valid for pointers. For example the following table shows what all arithmetic are possible
All other arithmetic operations like division / multiplication involving pointer variables isn’t allowed.
Addition/Subtraction involving pointers
When a value is decremented or incremented from a pointer variable the pointer is incremented or decremented by the size of type of value the pointer points to. For example
Reading pointer declarations
The general rule of reading pointer declarations is to start from the pointer variable and then move to right and then move to left building up the declaration. We’ll start with simpler ones
Pointer Tricks