In C, a pointer holds the address of an object stored in memory. The pointer then simply “points” to the object. The type of the object must correspond with the type of the pointer.
type *name; // points to a value of the specified type
type
refers to the data type of the object our pointer points to, and name
is just the label of the pointer. The *
character specifies that this variable is in fact, a pointer. Here is an example:
int *p; // integer pointer
string *q; // string pointer
The &
character specifies that we are storing the address of the variable succeeding it.
The *
character lets us access the value.
#include <stdio.h>int main(void) {int var = 10;int *p;p = &var; // p points to the address of varprintf("The address of p: %p\n", (void *) p);printf("The value of p: %d\n", *p);*p = 15; // update the value of pprintf("The new value of var is: %d\n", var); // var is updated!var = 20; // the value of var is updatedprintf("The new value of *p and var: %d\n", *p); // *p has been updated as well!}
So, why do we need pointers when we already have normal variables? Well, with pointers we have the power of creating new objects in dynamic memory rather than static memory. A pointer can create a new object in dynamic memory by using the malloc
command.
With malloc
, we need to specify the amount of bytes we want to reserve in dynamic memory. Since it is a void
method, we need to cast the pointer into the data type we want. Here’s the template for pointer declaration using malloc
:
p = (cast type*) malloc(size);
#include<stdio.h>#include<stdlib.h>int main() {int *p = (int*) malloc(sizeof(int)); // dynamic memory reserved for an integer*p = 10; // the object is assigned the value of 10printf("The value of p: %d\n", *p);int *q = p; // both pointers point to the same objectprintf("The value of q: %d\n", *q);int *arr = (int*) malloc(5 * sizeof(int)); // a dynamic array of size 5 is created.free(arr); // releases the designated memoryfree(p);}
Syntax | Purpose |
---|---|
int *p |
Declares a pointer p |
p = (int*) malloc(sizeof(int)) |
Creates an integer object in dynamic memory |
p = (int*) malloc(n * sizeof(int)) |
Creates a dynamic array of size n |
p = &var |
Points p to the var variable |
*p |
Accesses the value of the object p points to |
*p = 8 |
Updates the value of the object p points to |
p |
Accesses the memory address of the object p points to |
Free Resources