Back to course

Pointers Part 2: Pointers and Arrays

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 35: Pointers Part 2: Pointers and Arrays

In C, there is an intimate and crucial relationship between pointers and arrays. They are often treated interchangeably in expressions.

Array Name as a Pointer

When used in an expression (except when used with sizeof or &), an array name decays into a constant pointer to its first element.

Given: c int arr[5] = {10, 20, 30, 40, 50};

  • arr is equivalent to &arr[0] (the address of the first element).

Accessing Array Elements using Pointers

We can use pointer arithmetic (covered next) or array indexing on the pointer.

c int *ptr = arr; // ptr now holds the address of arr[0]

// Array indexing via array name: printf("%d\n", arr[2]); // 30

// Array indexing via pointer: printf("%d\n", ptr[2]); // 30

// Dereferencing with pointer arithmetic: printf("%d\n", *(arr + 2)); // 30 printf("%d\n", *(ptr + 2)); // 30

Pointers to Strings

Strings are commonly manipulated using pointers because a string literal ("Hello") is inherently a pointer to the first character of that literal.

c char *s = "C Programming"; // s points to 'C' printf("%s\n", s); // Prints the entire string until \0 printf("%c\n", *s); // Prints 'C' printf("%c\n", *(s + 2)); // Prints ' ' (space)

Key Takeaway: Understanding that arr[i] is syntactic sugar for *(arr + i) is essential for mastering C.