Module 3: Chapter 5 — Pointers
Pointers - Introduction
Definition
A pointer is a variable that stores the memory address of another variable. Instead of holding a direct value, it points to the location where the value is stored in memory.
Explanation
- Pointers allow direct access to memory locations.
- They are commonly used for arrays, functions, and dynamic memory.
- If one variable stores the address of another, it is said to point to that variable.
- Pointers are essential for efficient memory usage in C.
Pointers - example for better understanding
- What is a pointer? (a variable that stores an address)
-
&(address-of) and*(dereference) operators - Declaring and using pointers
int main() {
int a = 10;
int *p = & a; // pointer to a
printf("Value of a: %d\\n", a);
printf("Address of a: %p\\n", & a);
printf("Pointer p stores address: %p\\n", p);
printf("Value at address stored in p: %d\\n", *p);
return 0;
}
Practice:
- Print the address and value of different data types.
-
Change a variable's value using a pointer (
*p = 20;).
Pointer Variables
Definition
A pointer variable is a variable declared to store the address of another variable of a specific data type.
Syntax
type *pointer_name;
Explanation
typerepresents the base data type (int, char, float, etc.).- The
*symbol indicates that the variable is a pointer. - The base type defines how the pointer interprets the memory.
- An
int *pointer always assumes it points to an integer.
Pointer Operators
Definition
C provides two special operators for pointers: & (address-of) and * (dereference).
Syntax
m = &count;
q = *m;
Explanation
&returns the memory address of a variable.*returns the value stored at a given address.m = &countmeans m stores the address of count.q = *mmeans q gets the value stored at that address.
Pointer Expressions
Definition
Pointer expressions involve assignments, arithmetic, and comparisons using pointer variables.
Explanation
- Pointer expressions follow the same rules as normal expressions.
- They are evaluated based on the pointer’s base type.
- Arithmetic operations depend on the size of the data type.
- Incorrect pointer expressions can cause undefined behavior.
Pointer Assignments
Definition
Pointer assignment means copying the address stored in one pointer into another pointer of the same type.
Syntax
int x = 99;
int *p1, *p2;
p1 = &x;
p2 = p1;
Explanation
- Both pointers refer to the same memory location.
- Changing the value via one pointer affects the same variable.
- The addresses stored in both pointers will be identical.
- This is safe only when pointer types match.
Pointers and Undefined Behavior
Definition
Undefined behavior occurs when pointers are used incorrectly, leading to unpredictable program results.
Explanation
- Accessing memory with the wrong pointer type is unsafe.
- Reading partial data from larger data types causes errors.
- Invalid pointer arithmetic may corrupt memory.
- Always ensure pointer type matches the data being accessed.
Pointers and Arrays
Definition
In C, arrays and pointers are closely related. The name of an array represents the address of its first element, which can be assigned to a pointer.
Basic Idea
char str[80];
char *p1;
p1 = str;
Explanation
p1now points to the first element of the arraystr.- Array indexing and pointer arithmetic can access the same elements.
- Arrays start from index
0.
Accessing Elements
str[4]; /* using array indexing */
*(p1 + 4); /* using pointer arithmetic */
- Both expressions access the 5th element of the array.
p1 + 4moves the pointer to the 5th position.
Key Points
- C provides two ways to access arrays: indexing and pointers.
- Pointer-based access can be faster and more efficient.
- Professional C programmers often prefer pointers for array traversal.
Multiple Indirection (Pointers to Pointers)
Definition
Multiple indirection occurs when a pointer stores the address of another pointer, which in turn points to the actual data. This is commonly called a pointer to a pointer.
Concept Explanation
- A normal pointer stores the address of a variable.
- A pointer to a pointer stores the address of another pointer.
- The second pointer then points to the actual data value.
- More than two levels of indirection are rarely used.
- Excessive indirection makes code harder to read and debug.
Important Note
Multiple indirection should not be confused with data structures such as linked lists. They are different concepts, even though both use pointers.
Syntax
float **newbalance;
This declaration means newbalance is a pointer to a pointer to
a float, not a pointer to a float value directly.
Example
int x, *p, **q;
x = 10;
p = &x;
q = &p;
printf("%d", **q);
Explanation
pstores the address ofx.qstores the address of pointerp.**qaccesses the value ofx.- The output of the program is 10.
Initializing Pointers
Definition
Initializing a pointer means assigning it a valid memory address before using it. Using an uninitialized pointer can cause serious runtime errors.
Why Initialization Is Important
- Local (nonstatic) pointers contain garbage values if not initialized.
- Using such pointers may crash the program or the operating system.
- Global and static local pointers are automatically initialized to
null.
Null Pointer Concept
- A pointer that does not point to valid memory is usually set to
null. nullmeans the pointer points to nothing.- C guarantees that no valid object exists at address
0.
Syntax
char *p = 0;
int *q = NULL;
Explanation
- Assigning
0orNULLinitializes a pointer to null. NULLis a macro defined in standard header files like<stdio.h>.- Null pointers indicate unused or uninitialized pointers by convention.
Important Warning
int *p = 0;
*p = 10; /* wrong! */
- Dereferencing a null pointer is illegal.
- This usually causes a program crash.
- The compiler will not always report this as an error.
Practical Use of Null Pointers
- Used to mark unused pointers.
- Used to indicate the end of pointer-based data structures.
- Makes pointer-handling logic simpler and more efficient.