Introduction
A pointer in C is a variable that stores the memory address of another variable. Pointers are powerful tools for dynamic memory management, arrays, and function calls. Understanding pointers is essential for advanced C programming.
Key Points
1. Pointer Declaration
- Syntax:
dataType *pointerName; - Example:
int *ptr;
2. Pointer Initialization
- Assign the address of a variable using
&:int a = 10; int *ptr = &a;
3. Dereferencing a Pointer
- Access the value stored at the memory address using
*:printf("%d", *ptr); // Outputs 10
4. Null Pointer
- Pointer that does not point to any valid memory:
int *ptr = NULL;
5. Pointer Arithmetic
- Add/subtract integers to move to other memory locations:
ptr++; // Moves to next memory location of int
6. Pointers and Arrays
- Array name acts as a pointer to the first element:
int arr[3] = {10, 20, 30}; int *p = arr; // Points to arr[0] printf("%d", *(p + 1)); // Outputs 20
7. Advantages
- Efficient memory usage
- Dynamic memory allocation
- Allows passing large data to functions without copying
8. Limitations
- Incorrect use can cause memory leaks
- Can lead to segmentation faults
- Requires careful handling
Example Code
#include <stdio.h>
int main() {
int a = 10;
int *ptr = &a;
printf("Address of a: %p\n", ptr);
printf("Value of a using pointer: %d\n", *ptr);
return 0;
}