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 - example for better understanding

#include <stdio.h>
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:

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

Pointer Operators

Definition

C provides two special operators for pointers: & (address-of) and * (dereference).

Syntax

m = &count;
q = *m;

Explanation

Pointer Expressions

Definition

Pointer expressions involve assignments, arithmetic, and comparisons using pointer variables.

Explanation

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

Pointers and Undefined Behavior

Definition

Undefined behavior occurs when pointers are used incorrectly, leading to unpredictable program results.

Explanation

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

Accessing Elements

str[4];   /* using array indexing */
*(p1 + 4);  /* using pointer arithmetic */

Key Points

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

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

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

Null Pointer Concept

Syntax

char *p = 0;
int *q = NULL;

Explanation

Important Warning

int *p = 0;
*p = 10; /* wrong! */

Practical Use of Null Pointers