Pointers and memory management are fundamental concepts in C that allow direct manipulation of memory addresses, efficient data structures, and dynamic memory allocation. Understanding these concepts is crucial for writing optimized and efficient C programs. This tutorial covers pointers, pointer arithmetic, and dynamic memory management.
A pointer is a variable that stores the memory address of another variable. Declaring a pointer in C:
int *ptr; // Pointer to an integerExample of using a pointer:
#include <stdio.h>
int main() {
int num = 10;
int *ptr = # // Storing the address of num in ptr
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", &num);
printf("Value of ptr: %p\n", ptr);
printf("Value pointed by ptr: %d\n", *ptr);
return 0;
}Pointers support arithmetic operations:
ptr++ moves the pointer to the next memory location.ptr-- moves it to the previous memory location.#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30};
int *ptr = numbers;
printf("First value: %d\n", *ptr);
ptr++; // Move to next element
printf("Second value: %d\n", *ptr);
return 0;
}In C, memory is managed using:
malloc(): Allocates memory.calloc(): Allocates and initializes memory.realloc(): Resizes allocated memory.free(): Releases allocated memory.Example using malloc():
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int)); // Allocate memory
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
*ptr = 42;
printf("Allocated Value: %d\n", *ptr);
free(ptr); // Free memory
return 0;
}calloc() initializes memory to zero:
int *ptr = (int *)calloc(5, sizeof(int));realloc() changes memory size dynamically:
ptr = (int *)realloc(ptr, 10 * sizeof(int));To avoid memory issues:
free() dynamically allocated memory.NULL after freeing them.Practice using pointers with arrays, structures, and functions. Explore advanced memory management techniques for efficient programming.