Understanding Pointers & Memory in C
A pointer is a variable that stores the memory address of another variable. Pointers are essential for dynamic memory allocation, efficient array manipulation, and passing data by reference.
The Dereference & Address Operators
Use the & operator to get the memory address of a variable, and the * operator to access the value stored at that address.
Dynamic Memory with malloc and free
Use malloc() from <stdlib.h> to allocate heap memory at runtime. Always remember to call free() when finished to avoid memory leaks!
c Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int num = 42;
int *ptr = #
printf("Value: %d, Address: %p\n", *ptr, (void*)ptr);
int *arr = (int*)malloc(3 * sizeof(int));
if (arr != NULL) {
arr[0] = 10; arr[1] = 20; arr[2] = 30;
printf("Dynamic arr[1]: %d\n", arr[1]);
free(arr);
}
return 0;
}