Pointers
A pointer is a variable that can hold the address of another variable.
int* a; // `a` is a pointer to type int
double *ptrPi; // `ptrPi` is a pointer to type double
Address Resolution
The address-of operator &
is used to obtain the memory address of a variable.
#include <stdio.h>
int main() {
// Declare variables
int number = 42;
double pi = 3.14159;
char letter = 'A';
// Display the addresses of variables
printf("Address of number: %p\n", &number);
printf("Address of pi: %p\n", &pi);
printf("Address of letter: %p\n", &letter);
return 0;
}
The %p
format specifier is used in printf to print the memory addresses.
Dereference
The dereference operator *
is used to access the value stored at a particular memory address pointed to by a pointer.
For example:
int main() {
int number = 42;
double pi = 3.14159;
char letter = 'A';
int *ptrNumber = &number;
double *ptrPi = π
char *ptrLetter = &letter;
printf("Value of number: %d\n", *ptrNumber);
printf("Value of pi: %.5f\n", *ptrPi);
printf("Value of letter: %c\n", *ptrLetter);
return 0;
}
The dereference operator allows you to manipulate the values at the memory locations pointed to by pointers. It is an essential concept when working with pointers in C.
Pointer Arithmetic
When you perform arithmetic operations on pointers, the compiler adjusts the address based on the size of the data type the pointer is pointing to.
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int *ptr = numbers;
printf("Elements of the array using pointer arithmetic:\n");
for (int i = 0; i < 5; ++i) {
printf("Element %d: %d\n", i + 1, *(ptr + i));
}
int *thirdElementPtr = ptr + 2;
printf("\nAccessing the third element directly using pointer arithmetic: %d\n", *thirdElementPtr);
return 0;
}
Heap Allocation
Heap allocation in C involves dynamically allocating memory from the heap using functions like malloc
, calloc
, or realloc
.
#include <stdio.h>
#include <stdlib.h>
int main() {
// Dynamically allocate memory for an integer
// and return the pointer to its address
int* a = (int*)malloc(sizeof(int));
if (a) { // check if that the memory was allocated successfully
free(a); // free it manaully, otherwise it leads to memory leak
}
return 0;
}
Code Challenge
Write a C program that uses pointers to swap the values of two integers.