
Pointers in C
? Pointers in C
A pointer is a variable that stores the memory address of another variable. They are powerful tools that allow direct memory access and manipulation.
? Declaring a Pointer
Symbol Meaning *
Dereference operator (get value at address) &
Address-of operator (get address of variable)
? Example Program
#include <stdio.h>int main() { int x = 100; int *ptr = &x; printf("Value of x: %d\n", x); // 100 printf("Address of x: %p\n", &x); // address printf("Pointer value (ptr): %p\n", ptr); // address printf("Value pointed to by ptr: %d\n", *ptr); // 100 return 0;}
? Why Use Pointers?
Pass variables by reference to functions
Dynamic memory allocation (
malloc
,calloc
, etc.)Work with arrays and strings
Build complex structures like linked lists, trees
?? Common Mistakes
Uninitialized pointers (
int *p;
) – leads to undefined behavior.Dangling pointers – pointing to memory that has been freed.
Memory leaks – not freeing memory allocated on the heap.
? Pointer Types
Type | Example |
---|---|
Pointer to int | int *p; |
Pointer to char | char *str; |
Void pointer | void *ptr; |
Pointer to pointer | int **pp; |