*
symbol before the variable name. For example: int *ptr;
&
operator can be used to get the memory address of a variable, and the dereference operator (*
) is used to access the value stored at that memory location.[]
. For example: int arr[5];
#include <stdio.h>
int main() {
int num = 10;
int *ptr = #
printf("The value stored at the address %p is: %d\n", ptr, *ptr);
return 0;
}
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("The value at index 2 of the array is: %d\n", arr[2]);
return 0;
}
What causes it: Dereferencing a null pointer.
#include <stdio.h>
int main() {
int *ptr = NULL;
printf("%d\n", *ptr); // Segmentation fault!
return 0;
}
Solution: Ensure the pointer points to a valid memory location before dereferencing it.
#include <stdio.h>
int main() {
int num = 10;
int *ptr = #
printf("%d\n", *ptr); // No segmentation fault!
return 0;
}
Why it happens: The pointer is not initialized or does not point to a valid memory location.
How to prevent it: Always check if the pointer is null before dereferencing it.
What causes it: Accessing an array element beyond its bounds.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("%d\n", arr[6]); // Array Out of Bounds Error!
return 0;
}
Solution: Access elements only within the defined array bounds.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("%d\n", arr[4]); // No Array Out of Bounds Error!
return 0;
}
Why it happens: The index used to access the array element is greater than or equal to the number of elements in the array.
How to prevent it: Always check the bounds when accessing array elements.