Pointers in C
Pointers are variables that store the memory address of another variable.
They give powerful control over memory, data structures, arrays, strings, and functions.
Why Pointers?
- Access memory directly
- Modify values using reference
- Efficient for arrays & strings
- Needed for dynamic memory allocation
- Essential in data structures (Linked List, Treesβ¦)
Pointer Declaration
int *p; float *q; char *str;
Address (&) and Dereference (*) Operators
- & β gives address
- * β gives value at that address
int x = 10;
int *p = &x;
printf("%p", p); // address
printf("%d", *p); // value
Types of Pointers
- Null Pointer
- Void Pointer
- Wild Pointer
- Dangling Pointer
- Function Pointer
Pointer Memory Size
- 4 bytes in 32-bit
- 8 bytes in 64-bit
Size is same for all pointer types.
Pointer Rules
- Always initialize pointers
- Never access freed memory
- Return pointer only to dynamic memory
- Pointer must match data type
Pointer Examples (15 Examples)
1. Basic Pointer
#include <stdio.h>
int main(){
int x = 10;
int *p = &x;
printf("%d", *p);
return 0;
}
2. Print Address
#include <stdio.h>
int main(){
int x = 42;
printf("%p", &x);
return 0;
}
3. Modify Value Using Pointer
#include <stdio.h>
int main(){
int a = 5;
int *p = &a;
*p = 50;
printf("%d", a);
return 0;
}
4. Pointer to Float
#include <stdio.h>
int main(){
float n = 3.14;
float *p = &n;
printf("%.2f", *p);
return 0;
}
5. Pointer to Char
#include <stdio.h>
int main(){
char c = 'A';
char *p = &c;
printf("%c", *p);
return 0;
}
6. Null Pointer
#include <stdio.h>
int main(){
int *p = NULL;
printf("%p", p);
return 0;
}
7. Void Pointer
#include <stdio.h>
int main(){
int a = 20;
void *p = &a;
printf("%d", *(int*)p);
return 0;
}
8. Pointer to Pointer
#include <stdio.h>
int main(){
int x = 5;
int *p = &x;
int **pp = p;
printf("%d", **pp);
return 0;
}
9. Incrementing Pointer
#include <stdio.h>
int main(){
int a = 10;
int *p = &a;
p++;
printf("%p", p);
return 0;
}
10. Pointer with Array
#include <stdio.h>
int main(){
int arr[3] = {1,2,3};
int *p = arr;
printf("%d", *(p+1));
return 0;
}
11. Pointer in Function
#include <stdio.h>
void update(int *p){
*p = 100;
}
int main(){
int a = 10;
update(&a);
printf("%d", a);
return 0;
}
12. Swapping with Pointers
#include <stdio.h>
void swap(int *x, int *y){
int t = *x;
*x = *y;
*y = t;
}
int main(){
int a = 10, b = 20;
swap(&a,&b);
printf("%d %d", a, b);
return 0;
}
13. Pointer to String
#include <stdio.h>
int main(){
char *name = "Sourav";
printf("%s", name);
return 0;
}
14. Pointer Arithmetic on Array
#include <stdio.h>
int main(){
int arr[] = {10, 20, 30};
int *p = arr;
printf("%d", *(p+2));
return 0;
}
15. Dynamic Memory Address Check
#include <stdio.h>
#include <stdlib.h>
int main(){
int *p = (int*)malloc(sizeof(int));
*p = 500;
printf("%d", *p);
free(p);
return 0;
}