Pointers in C
In computers, memory stores information that the computer needs right now. In C, pointers are variables that store memory addresses. Memory addresses point to locations in memory, much like how a house address points to someone’s house.
Variables are stored in memory, so we can use pointers to access those variables. Pointers can be of a specific data type, like an integer pointer or a character pointer. They can also be of any data type, like a void pointer.
Declaring and initializing pointers
Here is how you declare an integer pointer in C:
int* intPtr;
As you can see, we have the data type int followed by an asterisk. The asterisk indicates that the variable is a pointer.
Below, we have an integer variable called foo which has the value 3.
Here is an example of assigning a memory address to a pointer:
int foo = 3;
int* intPtr;
intPtr = &foo;
The “&” in front of foo means “the memory address of”. Putting all of this together, intPtr = &foo says “assign the memory address of foo to the pointer intPtr”. Now, intPtr points to the address of foo. What if we want to use the pointer to find out the value of foo? To do that, we need to dereference the pointer.
Dereferencing pointers
Pointers are references to variables. If we want to access the variable itself, we dereference the pointer to that variable. To dereference means to access the value at the address that a pointer points to. So if the pointer intPtr points to foo, dereferencing intPtr would give the value of foo.
To dereference a pointer, we would type this:
*intPtr
Because intPtr points to foo, if we print both *intPtr and foo out, we would get the same values.
That is, if we ran the following code, the number 3 would be printed on both lines:
printf(“%d\n”,foo);
printf(“%d\n”,*intPtr);
Uses for pointers
Why use pointers in the first place? We can use pointers to do things only possible with pointers:
- Dynamic memory allocation
- Implementing data structures
- Letting functions change variable values (pass by reference)
- Pointers work as arrays and strings
More resources
Below are some more resources to learn about pointers in C: