4.1 Pointers
Pointers: -
- A pointer is a special variable that stores the memory address of another variable.
- Instead of holding a direct value (like 10 or 3.5), a pointer holds the location where the value is stored in memory.
- Pointers are powerful in C programming because they allow direct access to memory, dynamic memory allocation, and efficient data manipulation.
- Every variable in C is stored at a specific memory location, identified by a unique address.
- The address-of operator (&) is used to get the address of a variable.
- %p format specifier is used to print an address in pointer format.
Declaring Pointer Variables: -
- A pointer variable is declared using an asterisk (*) before the variable name.
- The data type of the pointer must match the data type of the variable it points to.
Initialization of Pointer Variables: -
- A pointer should always be initialized before using it.
- We can initialize a pointer by assigning it the address of a variable using the address-of operator (&).
- If a pointer is not initialized, it may contain a garbage address, which can cause runtime errors if dereferenced.
Accessing a Variable through
its Pointer: -
The dereference operator (*)
is used to access (read or modify) the value of the variable a pointer points
to. This process is called dereferencing.
Example: -
Output: -