Pointer Assignment 3 — Sum of Array Elements Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Sum of Elements in an Array Using Pointers

📑 On this page:
  • Arrays and Pointers — Why They're Related
  • Pointer Arithmetic on Arrays
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • Why an array name behaves like a pointer to its first element (array decay)
  • How pointer arithmetic (p + i, p++) walks through an array
  • Two ways to traverse an array with a pointer: indexed and advancing
  • How *(p + i) is exactly equivalent to arr[i]
  • How to write the same logic as a reusable function that takes a pointer and a length

Arrays and Pointers — Why They're Related

In C, the name of an array is almost the same as a pointer to its first element. When you write int arr[5] = {10, 20, 30, 40, 50};, the expression arr — when used in a value context — decays to a pointer of type int * that holds the address of arr[0]. That decay is why arr and &arr[0] print the same address, and why you can assign int *p = arr; without any cast.

The key insight is that arr[i] is defined to be exactly *(arr + i). It's not "similar to" — it is the same operation, by the language definition. The brackets are a notational convenience. Once you accept that, iterating over an array with a pointer is the same as iterating over it with an index — except you're computing the address arithmetic explicitly rather than letting the compiler do it for you.

This program uses that relationship: get a pointer to the first element, walk it forward one element at a time, and add each element to a running total.

💡 In one line: arr[i] and *(arr + i) are the same thing. The pointer version just makes that arithmetic explicit.

Diagram of an int array with a pointer p stepping through elements while a running sum accumulates the total

Pointer Arithmetic on Arrays

Expression Meaning Example (with int arr[5]; int *p = arr;)
pPointer to the first elementPoints at arr[0]
p + iPointer offset by i elementsp + 2 points at arr[2]
*(p + i)Value at the offset*(p + 2) is arr[2]
p[i]Same as *(p + i)p[2] is arr[2]
p++Advance pointer to next elementMoves from arr[0] to arr[1]
*p++Read current value, then advanceCommon idiom in loops
p < arr + nLoop termination checkTrue until p reaches one past the end

Two rules govern pointer arithmetic. First, adding i to p advances by i * sizeof(*p) bytes — not i bytes. That's why p + 1 reaches the next int even though int is usually 4 bytes. Second, you may compute the "one-past-the-end" pointer (arr + n) and compare against it, but you must never dereference it. Stepping exactly one past the end is legal for comparison; going further is undefined behaviour.

Complete C Program

Program: sum an array's elements through a pointer, then refactor into a function

#include <stdio.h>

/* Sum n elements starting at *p using indexed pointer arithmetic */
int sum_array(const int *p, int n) {
    if (p == NULL || n <= 0) {
        return 0;
    }
    int total = 0;
    for (int i = 0; i < n; i++) {
        total += *(p + i);        /* same as p[i] and arr[i] */
    }
    return total;
}

/* Sum n elements by advancing the pointer itself */
int sum_array_advancing(const int *p, int n) {
    if (p == NULL || n <= 0) {
        return 0;
    }
    const int *end = p + n;       /* one-past-the-end, safe to compute */
    int total = 0;
    while (p < end) {
        total += *p;               /* read current element */
        p++;                       /* move to next element */
    }
    return total;
}

int main(void) {
    int arr[6] = {10, 20, 30, 40, 50, 60};
    int n = 6;

    /* Pointer to the first element — the array name decays to int * */
    int *p = arr;

    /* Indexed approach inside main */
    int sum1 = 0;
    for (int i = 0; i < n; i++) {
        sum1 += *(p + i);
    }
    printf("Sum via *(p + i)        = %d\n", sum1);

    /* Advancing approach inside main */
    int *q = arr;
    int sum2 = 0;
    for (int i = 0; i < n; i++) {
        sum2 += *q;
        q++;
    }
    printf("Sum via *q (advancing q)= %d\n", sum2);

    /* Reusable functions */
    printf("sum_array(arr, n)       = %d\n", sum_array(arr, n));
    printf("sum_array_advancing     = %d\n", sum_array_advancing(arr, n));

    return 0;
}
                                    

Program Output

Sum via *(p + i)        = 210
Sum via *q (advancing q)= 210
sum_array(arr, n)       = 210
sum_array_advancing     = 210
                                

All four methods compute the same total: 10 + 20 + 30 + 40 + 50 + 60 = 210. The differences are purely stylistic and syntactic — the underlying address arithmetic is identical.

Step-by-Step Explanation

Let's walk through the program, then look at the subtle points that trip people up.

1. int arr[6] = {10, 20, 30, 40, 50, 60};

The array occupies six contiguous int slots in memory. Suppose arr starts at address 0x2000 and each int is 4 bytes; then arr[0] is at 0x2000, arr[1] at 0x2004, arr[2] at 0x2008, and so on. The name arr used in an expression decays to the address 0x2000 and type int *.

2. int *p = arr;

p now holds 0x2000 and points at arr[0]. The compiler may warn if you mix types (e.g., assigning an int * to a double *) but here the types match, so no cast is needed.

3. sum1 += *(p + i);

On each iteration, p + i computes "the address i ints past p." Since p points to arr[0], p + 0 is arr[0], p + 1 is arr[1], and so on. The * operator dereferences that address to fetch the value. This is the same as writing arr[i]. On each iteration total grows by the current element.

4. sum2 += *q; q++;

A different idiom. Instead of computing p + i fresh each time, we move q itself forward by one element per step. q++ doesn't mean "add one byte"; it means "advance by one element of the pointer's type." For an int * on a typical machine that's a 4-byte jump. After the loop, q points one past the last element. This is exactly the loop-over-a-range pattern you'll see in real C code.

5. sum_array(const int *p, int n)

Wrapping the logic in a function makes it reusable. The parameter const int *p means "a pointer to const int" — the function promises not to modify the elements through p. That's a helpful contract for readers and enables the compiler to catch accidental writes. We pass arr — which decays to int * — and the compiler happily converts to const int * (adding const is allowed). Passing an explicit length n is necessary because a raw pointer does not carry the size of the array with it.

6. sum_array_advancing — the one-past-the-end idiom

Here the loop is driven by a pointer comparison rather than an index. end = p + n computes the address one element past the array's end. This is legal — you may compute one-past-the-end even though you must not dereference it. The while (p < end) condition stops exactly when p reaches end. This is idiomatic C: your loop body processes *p, then p++ moves to the next element, and the comparison halts before touching anything out of bounds.

7. Why sizeof wouldn't work here

A common beginner mistake is to try to compute n inside a function with sizeof(p) / sizeof(*p). Inside sum_array, p is a pointer (probably 8 bytes); *p is an int (probably 4 bytes). The result would be 2, not 6 — completely wrong. sizeof on an array works only in the array's own scope, where the compiler knows the declared size. Once it decays to a pointer, that information is gone. Hence passing n explicitly. (In C99+, you can use sizeof arr / sizeof arr[0] in main where arr is declared, but not inside a function that receives arr as a parameter.)

8. Const correctness — why const int *p?

When a function only reads through a pointer, marking the pointer's target const documents that promise and lets the caller pass read-only data without warnings. It also helps the compiler catch a bug like *p = 0; inside sum_array — a bug you almost certainly don't intend. The const here is part of the pointer's pointee type (const int), not of the pointer itself. A const int * can be reassigned to point elsewhere, but the int it points to cannot be modified through it.

9. Overflow — what if the sum is huge?

int typically holds up to about 2.1 billion. If the array has many large elements, the sum can overflow — undefined behaviour for signed integers. For general-purpose summing, use long long for the accumulator:

long long sum_array(const int *p, int n) {
    long long total = 0;
    for (int i = 0; i < n; i++) total += *(p + i);
    return total;
}
                                

This is a defensive habit worth forming early. Beginner programs rarely trigger overflow, but real data often does.

10. What if the array is empty or the pointer is NULL?

The function guards against both. If n <= 0, we return 0 without touching p. If p == NULL, likewise. Without those checks, a caller who passes an empty array would still be safe (the loop never executes), but a caller who passes NULL with n > 0 would trigger undefined behaviour — usually a segmentation fault. Two cheap checks make the function robust against common misuse.

🎯 Remember this: p + i does not add i to the address in bytes — it adds i times the size of the pointed-to type. That single fact explains almost all pointer arithmetic. And array-to-pointer decay means arr[i] and *(arr + i) are equivalent by definition, not by coincidence.

Frequently Asked Questions

1. Is arr really a pointer?

Not quite. arr is an array, and arrays are not pointers. But in most expressions, arr decays to a pointer to its first element. So int *p = arr; works because the right side decays to int *. You cannot, however, write arr = p; — arrays are not assignable. And sizeof arr gives the total size of the array (e.g., 24 bytes for 6 ints), while sizeof p gives the size of the pointer (typically 8 bytes).

2. Which is faster — p[i] or *(p + i)?

Neither. They compile to exactly the same code. The brackets are purely a notational convenience. Some people find p[i] easier to read when the index represents "position i"; others find *(p + i) clearer when the offset is meaningful. Choose what makes the intent most obvious to the next reader.

3. Can I use -1 to reach the previous element?

You can add negative offsets as long as the resulting pointer stays within the same array. If p points at arr[3], then p[-1] is arr[2]. But if you add an offset that goes outside the array's bounds, the pointer arithmetic itself is undefined behaviour — even if you never dereference. C does not guarantee anything about out-of-bounds pointer values.

4. What happens if I write while (p != end) instead of p < end?

It works fine for arrays accessed front-to-back. But while (p < end) is more robust: if something accidentally advances p past end, the != version might loop forever or walk off into memory. The < version terminates the moment p reaches end and never dereferences past it. Prefer < in general code.

5. Why does sum_array(arr, n) not need an &?

Because arr decays to a pointer. Passing arr is the same as passing &arr[0] — both are an int * that points at the first element. If you wrote &arr instead, you'd get a pointer to the entire array (type int (*)[6]), which is a different beast. The function's const int * parameter expects the decayed form, so arr is correct.

6. Can I sort or modify the array through the pointer?

Yes, as long as the parameter is not const. Writing *(p + i) = 0; modifies the array element in place, and the caller sees the change. This is exactly how functions like qsort and memset work. For summing, we use const to communicate that the function is read-only — good practice whenever possible.

💡 Tip: This "sum through a pointer" pattern generalizes immediately. Replace total += *p with if (*p > max) max = *p and you have a maximum-finder. With if (*p < min) min = *p, a minimum-finder. With if (*p == key) return i, a linear search. All of those are the next few assignments in the series — and they all use the same pointer walk.

📖 Related Tutorials

  • 2. Swap Two Numbers Using Pointers
  • 4. Reverse an Array Using Pointers
  • 9. Linear Search in an Array Using Pointers
  • 10. Binary Search in a Sorted Array Using Pointers
  • 16. Find the Maximum Element Using Pointers
  • 17. Find the Minimum Element Using Pointers
  • The Pointer To An Array
  • All 30 Pointer Assignments

Previous Topic: -->> 2. Swap Two Numbers Using Pointers   ||   Next Topic: -->> 4. Reverse an Array Using Pointers


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.