Pointers let you work directly with memory addresses. But if used wrong, they cause bugs or crashes.
0
0
Common pointer errors
Introduction
When you want to access or change data stored in different parts of memory.
When you need to work with arrays or strings efficiently.
When you want to pass large data to functions without copying it.
When you want to create dynamic data structures like linked lists.
When you want to share data between functions safely.
Syntax
C
int *ptr; // declares a pointer to an int ptr = &var; // ptr now holds the address of var *ptr = 10; // changes the value at the address ptr points to
A pointer stores a memory address, not the actual value.
Using * (dereference) accesses the value at the pointer's address.
Examples
Prints the value of x using a pointer.
C
int x = 5; int *p = &x; printf("%d\n", *p);
Checks if pointer is not NULL before using it to avoid errors.
C
int *p; p = NULL; if (p != NULL) { *p = 10; }
Accesses the second element of an array using pointer arithmetic.
C
int arr[3] = {1, 2, 3}; int *p = arr; printf("%d\n", *(p + 1));
Sample Program
This program shows two common pointer errors: using an uninitialized pointer and dereferencing a NULL pointer. It avoids crashes by initializing pointers and checking for NULL before use.
C
#include <stdio.h> int main() { int *ptr; // pointer declared but not initialized int x = 10; // Common error: using uninitialized pointer // *ptr = 5; // This would cause a crash ptr = &x; // pointer now points to x *ptr = 20; // changes x to 20 printf("Value of x: %d\n", x); // Common error: dereferencing NULL pointer ptr = NULL; if (ptr != NULL) { *ptr = 30; // safe because we checked } else { printf("Pointer is NULL, cannot dereference.\n"); } return 0; }
OutputSuccess
Important Notes
Always initialize pointers before using them.
Never dereference a pointer that is NULL or uninitialized.
Use checks like if (ptr != NULL) to avoid crashes.
Summary
Pointers hold memory addresses and must be handled carefully.
Common errors include using uninitialized pointers and dereferencing NULL pointers.
Always initialize pointers and check for NULL before using them.