Pointers in C
A pointer is a variable that stores the memory address of another variable.
---
Pointer Basics
int a = 10;
int *p; /* pointer declaration */
p = &a; /* p holds address of a */
printf("%d\n", a); /* value: 10 */
printf("%p\n", p); /* address of a */
printf("%d\n", *p); /* dereference: value at address = 10 */
Operators:
&(address-of) — gives the address of a variable*(dereference) — gives the value at the address
---
Pointer Arithmetic
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; /* points to arr[0] */
printf("%d\n", *p); /* 10 */
printf("%d\n", *(p+1)); /* 20 */
printf("%d\n", *(p+2)); /* 30 */
p++; /* now points to arr[1] */
---
Pointer and Arrays
int arr[3] = {1, 2, 3};
int *p = arr;
/* Both are equivalent: */
printf("%d\n", arr[1]); /* using array notation */
printf("%d\n", *(p+1)); /* using pointer arithmetic */
---
Pointer to Pointer
int a = 10;
int *p = &a;
int **pp = &p;
printf("%d\n", **pp); /* 10 */
---
NULL Pointer
int *p = NULL; /* pointer pointing to nothing */
if (p == NULL) {
printf("Pointer is null\n");
}
---
Pointer as Function Argument (Call by Reference)
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
swap(&x, &y);
printf("x=%d y=%d\n", x, y); /* x=10 y=5 */
}
---
Dynamic Memory Allocation
#include <stdlib.h>
int *p = (int *)malloc(5 * sizeof(int)); /* allocate 5 ints */
if (p == NULL) {
printf("Memory allocation failed\n");
}
p[0] = 10;
p[1] = 20;
free(p); /* always free allocated memory */
| Function | Purpose |
|---|---|
malloc(size) | Allocate uninitialized memory |
calloc(n, size) | Allocate zero-initialized memory |
realloc(ptr, size) | Resize allocated memory |
free(ptr) | Release allocated memory |