C Access Memory
1. Accessing Memory Using Pointers
-
A pointer stores the address of a variable.
-
Use dereferencing (
*) to access or modify the value at that memory address.
Syntax:
2. Example: Pointer Access
Output:
*ptraccesses the memory location ofa.
3. Accessing Dynamically Allocated Memory
-
After allocating memory with
mallocorcalloc, use pointer arithmetic or dereferencing to access elements.
Output:
Array notation
arr[i]is equivalent to*(arr + i).
4. Accessing Memory in Structures via Pointers
Output:
Use
->operator to access struct members via pointer.
5. Pointer Arithmetic for Memory Access
-
Pointers can be incremented or decremented to traverse memory:
Output:
6. Key Points About Accessing Memory in C
-
Pointers store addresses of variables or allocated memory.
-
Use
*ptrto read/write the value at that memory location. -
Array elements can be accessed using array notation (
arr[i]) or pointer arithmetic (*(arr + i)). -
For structures, use dot
.for normal variables and arrow->for pointers. -
Always ensure the pointer points to valid memory before accessing it.
