Unit 11: Pointers

Table of Contents

1. Introduction to Pointers

A Pointer is a special variable that stores the memory address of another variable. Instead of holding a direct value like an integer or a character, a pointer "points" to the location where a value is stored in the computer's memory.

[Image of pointer variable pointing to a memory address of another variable]

2. Pointer Data Type and Declaration

A pointer must be declared with a data type that matches the type of the variable it points to. This is because the compiler needs to know how many bytes of memory to read when accessing the value at that address.

Syntax:

data_type *pointer_name;

Example:

3. Initialization of Pointers

Initialization is the process of assigning a memory address to a pointer variable. This is done using the Address-of Operator (&).

Example:

int num = 10;
int *ptr;     // Declaration
ptr = #   // Initialization (ptr now stores the address of num)
    
Warning: Always initialize pointers. A pointer that is declared but not initialized is called a Wild Pointer and contains a random memory address, which can lead to system crashes.

4. Accessing Values Using Pointers

You can access the actual value stored at the memory address held by a pointer using the Dereferencing Operator (*), also known as the Indirection Operator.

Example:

int x = 25;
int *p = &x;
printf("Value of x: %d", *p); // Output: 25
    

In the above code, *p tells the computer to "go to the address stored in p and get the value located there."

5. Pointer Expressions and Arithmetic

Pointer arithmetic allows you to perform addition and subtraction on pointers. However, unlike regular math, pointer arithmetic is based on the size of the data type it points to.

Rules of Pointer Arithmetic:

Formula for Addition:
New_Address = Current_Address + (n * Size_of_Data_Type)

6. Operations on Pointers

Beyond basic arithmetic, several other operations can be performed on pointers:

7. Exam Focus Enhancements

Exam Tips
Common Mistakes
Frequently Asked Questions

Q: What is the size of a pointer variable?
A: The size of a pointer is independent of the data type it points to. It depends on the architecture of the computer (usually 4 bytes on a 32-bit system and 8 bytes on a 64-bit system).

Q: Why do we use pointers?
A: Pointers allow for efficient handling of arrays, dynamic memory allocation, and the ability to return multiple values from a function via call-by-reference.

Q: Can we add two pointers together?
A: No. Adding two memory addresses is logically meaningless and prohibited in C.