Pointers in C
Pointers in C are variables that store the memory address of another variable. They are powerful tools for dynamic memory management, efficient array handling, and function operations.
1. Pointer Basics
A pointer is declared by using the * operator before its name. It stores the address of a variable.
- Example: int x = 10; int *ptr = &x; printf("%d", *ptr); // Output: 10
2. Pointer Initialization
Pointers must be initialized to the address of a variable or NULL before using them to avoid undefined behavior.
- Example: int a = 5; int *p = &a; int *q = NULL;
3. Dereferencing a Pointer
Dereferencing a pointer means accessing the value stored at the memory address it points to using the * operator.
- Example: int a = 20; int *ptr = &a; *ptr = 30; printf("%d", a); // Output: 30
4. Pointer Arithmetic
Pointers can be incremented, decremented, or used in arithmetic to navigate memory locations of arrays or structures.
- Example: int arr[3] = {1,2,3}; int *ptr = arr; ptr++; printf("%d", *ptr); // Output: 2
5. Pointers and Arrays
Arrays and pointers are closely related. The name of an array acts as a pointer to its first element.
- Example: int arr[3] = {10,20,30}; int *p = arr; printf("%d", *(p+1)); // Output: 20
6. Pointers to Pointers
A pointer to pointer stores the address of another pointer. It allows multiple levels of indirection.
- Example: int a = 5; int *p = &a; int **pp = &p; printf("%d", **pp); // Output: 5
7. Function Pointers
Function pointers store the address of a function and can be used to call the function indirectly.
- Example: int add(int a,int b){ return a+b; } int (*fp)(int,int) = add; printf("%d", fp(2,3)); // Output: 5
8. Pointer to Structure
Pointers can point to structures, allowing access to structure members using the -> operator.
- Example: struct Point { int x; int y; } p1 = {1,2}; struct Point *ptr = &p1; printf("%d", ptr->x); // Output: 1
9. Null Pointers
A null pointer is a pointer that points to nothing. It is used to initialize pointers safely.
- Example: int *ptr = NULL; if(ptr == NULL) printf("Pointer is null");
10. Memory Allocation with Pointers
Dynamic memory can be allocated using malloc, calloc, or realloc functions and accessed through pointers.
- Example: int *arr = (int*) malloc(5 * sizeof(int)); free(arr);
11. Void Pointer
Void pointers are generic pointers that can point to any data type. They must be typecast before dereferencing.
- Example: int x = 10; void *vp = &x; printf("%d", *(int*)vp); // Output: 10
Codecrown