Back to C Programming
2026-07-147 min read

C - Pointer vs Array

Learn C - Pointer vs Array step by step with clear examples and exercises.

Why This Matters

In this tutorial, we will delve into the intricacies of pointers and arrays in C programming, understanding their differences, advantages, and applications. Mastering these fundamental concepts is essential for writing efficient code, solving complex problems, and excelling in coding interviews.

Why This Matters

Understanding pointers and arrays is crucial for mastering C programming. These data structures are the building blocks of many algorithms and data structures used in software development. Knowing how to use them effectively can help you write efficient code, optimize performance, and tackle complex problems. Additionally, familiarity with pointers and arrays will be essential when encountering bugs or issues during debugging sessions or interviews.

Prerequisites

Before diving into the core concept, it is important that you have a good understanding of:

  • Basic C syntax and data types
  • Variables, constants, and operators
  • Control structures such as loops and conditional statements
  • Function definitions and calls
  • Data structures like structs and unions (optional but recommended)

Core Concept

Arrays

An array is a collection of elements of the same data type stored in contiguous memory locations. The first element's index is 0, and the size of an array can be determined using the sizeof operator. Here's an example of a simple array:

int arr[5] = {1, 2, 3, 4, 5};

In this example, we have created an array called arr with five integers. Each element can be accessed using its index in square brackets, for instance:

printf("%d", arr[0]); // Outputs: 1

Multidimensional Arrays

Multidimensional arrays are used to store a collection of data where each element can be thought of as an array itself. They are created by declaring an array of arrays, as shown below:

int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

In this example, we have created a 3x4 matrix called matrix. Each row can be accessed using its index in square brackets, and each element within the row can be accessed using another set of square brackets. For instance:

printf("%d", matrix[1][2]); // Outputs: 6

Pointers

A pointer is a variable that stores the memory address of another variable. In C, we declare pointers by prefixing the data type with a *. Here's an example of declaring and initializing a pointer to an integer:

int num = 10;
int *ptr = #

In this example, we have declared a variable called num and assigned it the value 10. We then created a pointer called ptr that points to the memory address of num. To access the value stored in num using the pointer, you can use the dereference operator (*):

printf("%d", *ptr); // Outputs: 10

Pointer Arithmetic

Pointer arithmetic involves performing operations on pointers to manipulate their memory addresses. Here are some common pointer arithmetic operations:

  • Incrementing a pointer (ptr++, ptr += 1) moves the pointer to the next memory location of the same data type.
  • Decrementing a pointer (ptr--, ptr -= 1) moves the pointer to the previous memory location of the same data type.
  • Adding an integer to a pointer (ptr + n) moves the pointer n memory locations forward.
  • Subtracting an integer from a pointer (ptr - n) moves the pointer n memory locations backward.

Pointer to Pointers

A pointer to a pointer, often denoted as **, allows you to store the address of another pointer. This can be useful when dealing with multi-dimensional data structures or dynamically allocated memory. Here's an example:**

int num = 10;
int *ptr = #
int **ptr2 = &ptr;

In this example, we have created a pointer to a pointer called ptr2. It stores the address of the pointer ptr, which in turn points to the integer num. To access the value stored in num using ptr2, you can use the double dereference operator (**) as follows:**

printf("%d", **ptr2); // Outputs: 10

Pointer vs Array

While arrays and pointers are related concepts, they have some fundamental differences. An array is a fixed-size collection of elements, while a pointer can point to any memory location, regardless of its size or data type.

Arrays are accessed using their index, while pointers require the dereference operator (*) to access the value they point to. However, arrays can be treated as pointers in C, as demonstrated below:

int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr now points to the first element of arr
printf("%d", *ptr); // Outputs: 1

In this example, we have shown that an array can be treated as a pointer to its first element. This is why arrays and pointers share some similarities in their usage, but it's important to understand the differences between them for efficient coding practices.

Worked Example

Let's consider a simple problem: Write a program that finds the sum of all elements in an array using pointers.

#include <stdio.h>

void sumArray(int *arr, int size, int *total) {
for (int i = 0; i < size; ++i) {
*total += arr[i];
}
}

int main() {
int arr[5] = {1, 2, 3, 4, 5};
int total = 0;
sumArray(arr, sizeof(arr) / sizeof(arr[0]), &total);
printf("The sum of the array elements is: %d\n", total);
return 0;
}

In this example, we have defined a function sumArray() that takes an array, its size, and a pointer to a total variable as arguments. The function iterates through the array using a for loop and adds each element to the running total pointed to by the total pointer. In the main() function, we create an array, initialize a total variable, call sumArray() with appropriate arguments, and print the final sum.

Common Mistakes

  1. Forgetting to initialize arrays: If you don't initialize an array, all its elements will contain garbage values.
int arr[5]; // arr contains garbage values
  1. Accessing out-of-bounds array elements: This can lead to undefined behavior and potential security vulnerabilities.
int arr[5] = {1, 2, 3, 4, 5};
printf("%d", arr[6]); // Undefined behavior
  1. Not understanding the difference between arrays and pointers: Misusing arrays as pointers or treating pointers like arrays can lead to unexpected results and bugs.
  1. Failing to properly allocate memory for dynamically allocated arrays or structures, leading to memory leaks or undefined behavior.
  1. Incorrectly using pointer arithmetic, such as incrementing a pointer beyond the end of an array or performing operations on pointers with incompatible data types.
  1. Not checking for null pointers before dereferencing them, which can lead to segmentation faults or other runtime errors.

Practice Questions

  1. Write a function that finds the maximum element in an array using pointers and without using built-in functions like max().
  2. Implement a program that sorts an array of integers using bubble sort algorithm, using pointers to iterate through the array.
  3. Given two arrays, write a function that checks if they are equal or not (element-wise comparison) using pointers.
  4. Write a function that dynamically allocates memory for a two-dimensional array and initializes it with zeros.
  5. Implement a program that finds the second largest number in an array using pointers, without using any built-in functions like secondLargest().
  6. Write a function that reverses the order of elements in an array using pointers and pointer arithmetic.
  7. Given an array of integers, write a function that returns the index of the first occurrence of a specific value using pointers and linear search algorithm.
  8. Implement a program that finds all pairs of numbers in an array whose sum equals a given target number using pointers and two-pointer technique.
  9. Write a function that calculates the product of all elements in an array using pointers and recursion.
  10. Given an array of strings, write a function that sorts the array lexicographically using pointers and bubble sort algorithm.

FAQ

Can I change the value of an element in an array using a pointer?

Yes, you can modify the value of an array element by using a pointer and dereferencing it.

How can I create a two-dimensional array in C?

To create a two-dimensional array, you need to declare an array of arrays:

int arr[3][4]; // A 3x4 two-dimensional array

What is the difference between sizeof(arr) and sizeof(arr)/sizeof(arr[0])?

sizeof(arr) returns the size of the entire array in bytes, while sizeof(arr)/sizeof(arr[0]) calculates the number of elements in the array. In this case, it will return the number of rows if arr is a two-dimensional array.

How can I dynamically allocate memory for an array in C?

You can use the malloc() function to dynamically allocate memory for an array:

int *arr = malloc(sizeof(int) * size);

What is the purpose of the null pointer (NULL)?

The null pointer, denoted as NULL, is a special value that represents the absence of a valid memory address. It can be used to indicate that a pointer does not point to any valid data or that an array has no elements.

What are some common pitfalls when using pointers in C?

Some common pitfalls include forgetting to initialize pointers, accessing out-of-bounds memory, leaking memory due to improper allocation and deallocation, and using pointers incorrectly in control structures like loops and conditional statements.

How can I check if a pointer is null in C?

You can use the == NULL or != NULL comparison operator to check if a pointer is null:

if (ptr == NULL) {
// Handle null pointer case
} else {
// Process valid pointer
}