Pointers in C
Pointers in C
Introduction to Pointers
A pointer is a variable that stores the memory address of another variable. Instead of holding a data
value directly, a pointer "points" to the location where a value is stored. This is a powerful feature in
To declare a pointer, use the * operator along with the data type:
#include <stdio.h>
int main() {
return 0;
Pointer Arithmetic
Pointer arithmetic is a way to move through arrays and memory. When adding or subtracting to a
#include <stdio.h>
int main() {
return 0;
An array name itself acts like a pointer to the first element, making array elements accessible via
pointer arithmetic.
#include <stdio.h>
int main() {
int arr[] = {5, 10, 15, 20};
return 0;
#include <stdio.h>
*a = *b;
*b = temp;
int main() {
swap(&x, &y);
return 0;
}
Pointers to Pointers
A pointer to a pointer is used for handling multidimensional arrays and memory management in
#include <stdio.h>
int main() {
return 0;
Dynamic memory allocation functions like malloc, calloc, and free in C make use of pointers for
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
ptr = (int *)malloc(n * sizeof(int));
if (ptr == NULL) {
return 1;
ptr[i] = i + 1;
free(ptr);
return 0;
Advanced Examples
#include <stdio.h>
#include <stdlib.h>
int main() {
matrix[i][j] = i * cols + j;
}
}
printf("\n");
free(matrix[i]);
free(matrix);
return 0;
Conclusion
Pointers in C provide a powerful way to access and manipulate memory. Mastering pointers is
crucial for effective C programming, especially for dynamic memory allocation, data structures, and
system-level programming.