Pointer Assignment 24 — Insert an Element into an Array Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Insert an Element into an Array Using Pointers — Shifting Right Through a Pointer Pair

📑 On this page:
  • How Pointer-Based Array Insertion Works
  • The Three Steps of the Insertion
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to insert an array element by shifting subsequent elements right
  • Why the shift must go backward (from the end) to avoid overwriting data
  • How to use two pointers (src and dst) to express the shift compactly
  • Why the length must be passed by pointer — int arrays don't carry their size
  • How to handle the "insert at the front" and "append at the end" edge cases

How Pointer-Based Array Insertion Works

Inserting an element at a given position means creating a gap for it by moving the existing elements after that position one slot to the right. If you insert at index 2 in [10, 20, 40, 50], the 40 moves to index 3, the 50 moves to index 4, and the slot at index 2 is then filled with the new value. The array's length increases by one, and the old last slot becomes a new valid element.

The critical detail is the order of the shift. When shifting right, you must start from the last element and work backward toward the insertion point. If you started from the insertion point and worked forward, you would overwrite the element you were about to copy. For example, copying arr[2] into arr[3] destroys the old arr[3], and the next iteration would copy the (now-lost) old arr[3] into arr[4] — producing a duplicate instead of a shift. Working backward avoids this: you copy arr[4] into arr[5] first, then arr[3] into arr[4], then arr[2] into arr[3] — each destination is empty (or about to be vacated) when you write to it.

The pointer version expresses this backward walk naturally. Let dst = arr + *n (one past the current last element) and src = arr + *n - 1 (the current last element). On each iteration, *dst = *src moves one element right, then dst-- and src-- move both pointers left. When dst reaches arr + pos, the gap is open and the new value goes in at arr + pos. The length is then incremented. The entire operation is O(n - pos) time and O(1) extra space — the same complexity as the array-index version, just with different notation.

💡 In one line: Shift elements right from the end backward, then write the new value at the target position, then increment the length. Working backward is what makes the shift safe.

Diagram showing two pointers src and dst walking right-to-left over an array, copying src into dst to shift all elements one position right and open a gap for insertion

The Three Steps of the Insertion

Step Pointer operation Effect
1. Validateif (arr == NULL || pos < 0 || pos > *n || *n >= capacity) return -1;Reject impossible insertions before writing anything
2. Shift right (backward walk)for (int *dst = arr + *n, *src = dst - 1; dst > arr + pos; dst--, src--) *dst = *src;Every element at or after pos moves one slot right, opening a gap
3. Write and growarr[pos] = value; (*n)++;The new element fills the gap; the length grows by one

The shift loop is the core, and its backward direction is essential. The condition dst > arr + pos says "keep copying until dst reaches the insertion point." At that point, dst points to the slot where the new value will go, and the loop has already moved every element that needs moving. Writing arr[pos] = value then fills the gap. The length increment (*n)++ is the final touch — from the caller's perspective, the array now has one more valid element.

The valid positions for insertion are 0 through *n inclusive. pos = 0 inserts at the front (every existing element shifts right). pos = *n appends at the end (no shift happens, because the "gap" is already past the last element). Both edge cases are handled by the same loop, with the boundary conditions doing the right thing: for pos = 0, the loop runs *n times; for pos = *n, it runs zero times. There's no need to special-case either.

Complete C Program

Program: insert an element at a given position using pointers (array and length updated in place)

#include <stdio.h>

#define MAX 100

/* Insert value at index pos in arr, shifting later elements right.
   Returns 0 on success, -1 if pos is out of range or the array is full.
   The new length is written back through n. */
int insert_at(int *arr, int *n, int pos, int value) {
    if (arr == NULL || n == NULL || pos < 0 || pos > *n || *n >= MAX) {
        return -1;
    }

    /* Shift elements right from the end, so we never overwrite
       an element before it has been copied. */
    int *dst = arr + *n;       /* one past the current last element */
    int *src = dst - 1;        /* the current last element */

    while (dst > arr + pos) {
        *dst = *src;
        dst--;
        src--;
    }

    /* Fill the opened slot and grow the array. */
    arr[pos] = value;
    (*n)++;

    return 0;
}

/* Print the array by walking a pointer. */
void print_array(const int *arr, int n) {
    const int *p = arr;
    const int *end = arr + n;
    printf("[");
    while (p < end) {
        printf("%d", *p);
        p++;
        if (p < end) printf(", ");
    }
    printf("]\n");
}

int main(void) {
    int arr[MAX] = {10, 20, 40, 50};
    int n = 4;

    printf("Before: ");
    print_array(arr, n);

    /* Insert in the middle */
    if (insert_at(arr, &n, 2, 30) == 0) {
        printf("After inserting 30 at index 2: ");
        print_array(arr, n);
    }

    /* Insert at the front */
    if (insert_at(arr, &n, 0, 5) == 0) {
        printf("After inserting 5  at index 0: ");
        print_array(arr, n);
    }

    /* Append at the end */
    if (insert_at(arr, &n, n, 60) == 0) {
        printf("After appending 60 at end   : ");
        print_array(arr, n);
    }

    /* Invalid position */
    if (insert_at(arr, &n, 100, 999) != 0) {
        printf("Insert at index 100 failed (out of range).\n");
    }

    return 0;
}
                                    

Program Output

Before: [10, 20, 40, 50]
After inserting 30 at index 2: [10, 20, 30, 40, 50]
After inserting 5  at index 0: [5, 10, 20, 30, 40, 50]
After appending 60 at end   : [5, 10, 20, 30, 40, 50, 60]
Insert at index 100 failed (out of range).
                                

The output walks through the four cases. First, 30 is inserted at index 2 of [10, 20, 40, 50], shifting 40 and 50 right to make room. Then 5 is inserted at the front, shifting every element right. Then 60 is appended at the end (no shift needed). Finally, an out-of-range insert is attempted and rejected — the array is unchanged. The array grows from 4 elements to 5, then 6, then 7, in the first three cases, and stays at 7 in the last. The parentheses in the output help show the shifting visually: after each insertion, exactly one more element appears, and the existing elements retain their relative order.

Step-by-Step Explanation

Let's walk through the pointer and length mechanics.

1. The function signature

int insert_at(int *arr, int *n, int pos, int value) takes four parameters. arr is the array (decayed to a pointer to its first element). n is a pointer to the array's length, so the function can update the caller's length variable. pos is the index where the new value goes. value is the new element. The return value is int, signalling success (0) or failure (-1) — the same convention used by delete_at in the previous assignment.

2. Validation

if (arr == NULL || n == NULL || pos < 0 || pos > *n || *n >= MAX) return -1; checks everything that could go wrong. Null pointers are caller errors. pos < 0 is out of range on the low side. pos > *n is out of range on the high side — but note that pos == *n is valid, because appending at the end is a legitimate insert. The *n >= MAX check catches a full array; without it, writing to arr[*n] (the new last slot) would write past the allocated buffer, corrupting memory. All checks run before any write, so a failed insert leaves the array untouched.

3. Setting up the pointer pair

int *dst = arr + *n; points at the slot after the current last element — the new "one past the end" position. This is where the first copy will go. int *src = dst - 1; points at the current last element — the first source of a copy. Both pointers will walk left together, one copying at a time. The condition dst > arr + pos stops the walk when dst reaches the insertion point, which is where the new value will eventually go.

4. The shift loop

while (dst > arr + pos) { *dst = *src; dst--; src--; } is the core. Each iteration copies the source element to the destination slot, then moves both pointers one slot left. This repeats until dst is at arr + pos, at which point the slot at pos is "empty" — well, it still contains the old arr[pos], but that's about to be overwritten. The elements after pos have all moved right by one.

5. Why the shift must go backward

This is the single most important detail. Suppose you tried to shift forward (from pos toward the end):

/* WRONG — will produce duplicates instead of a shift */
for (int i = pos; i < *n; i++) {
    arr[i + 1] = arr[i];
}
                                

In this wrong version, the first iteration copies arr[pos] into arr[pos + 1], overwriting the value that was there. The next iteration copies arr[pos + 1] (which now holds the old arr[pos]) into arr[pos + 2], overwriting that. The result is that the element at pos duplicates all the way to the end, and all the original values after pos are lost. Working backward avoids this — each source value is read before its slot is overwritten by the next iteration's write.

6. Tracing [10, 20, 40, 50] with pos = 2, value = 30

n = 4, dst = arr + 4, src = arr + 3. The array is [10, 20, 40, 50, ?] — the slot at index 4 is uninitialised.

  • Iteration 1: *dst = *src → arr[4] = 50. Array becomes [10, 20, 40, 50, 50]. dst → index 3, src → index 2.
  • Iteration 2: arr[3] = 40. Array becomes [10, 20, 40, 40, 50]. dst → 2, src → 1.
  • dst == arr + pos == arr + 2, so dst > arr + pos is false. Loop exits.

Now arr[2] = 30 is written, giving [10, 20, 30, 40, 50]. Finally (*n)++ sets n = 5, and the array is complete.

7. Inserting at the front

With pos = 0, dst starts at arr + n and src at arr + n - 1. The loop runs n times — every existing element moves one slot right. After the loop, dst == arr, and the new value is written there. This is the most expensive case: it shifts the entire array, so O(n) time.

8. Appending at the end

With pos = *n, dst = arr + *n and src = arr + *n - 1. The loop condition dst > arr + pos is immediately false (both sides equal arr + *n), so the loop body never runs. Then arr[*n] = value is written — that's arr[pos] = value, which is exactly the right slot — and (*n)++ grows the array. This is O(1), the best case.

9. Why the last slot check matters

The validation *n >= MAX catches the case where the array is already full. Without it, arr[*n] = value would write to index MAX — one past the end of the array — which is undefined behaviour. In a small program with a large array and few insertions, this won't happen, but in a production library routine, overflow detection is essential. The function should either reject the insertion (as here) or grow the array (via realloc, if the array was dynamically allocated). The static MAX array in this program can't grow, so rejection is the only option.

10. Why the length is passed by pointer

The function changes two things: the array's contents (in place) and its length (through int *n). C functions can only return one value, so the length must come out through a pointer. This is the standard idiom for any operation that changes an array's size, and it's symmetric with the delete function — both take int *n and update it. The caller sees both the array and the new length after the call, which is what makes the function useful.

11. Complexity

The shift loop runs *n - pos times, and each iteration does O(1) work. So the time is O(n - pos) — O(n) in the worst case (insert at the front) and O(1) in the best case (append at the end). Space is O(1): a few local pointers and the value parameter. This is optimal for an array insertion: you can't insert into the middle without moving the elements after it, and moving them takes O(n) time in the worst case. The only way to do better asymptotically is to use a linked list (O(1) insertion once you have a pointer to the position, at the cost of O(n) search), which is a trade-off worth knowing.

12. Why use memmove instead of a loop?

In production code, you would use memmove(arr + pos + 1, arr + pos, (*n - pos) * sizeof(int)) to shift the elements right, then write the value. memmove handles the overlapping ranges correctly (which is exactly what "shifting right" is — an overlapping copy) and is often faster because implementations use SIMD instructions. But the assignment asks for a pointer-based solution, and writing the loop teaches you what memmove does under the hood. After you've written the loop, you understand why memmove is the right library function for this kind of shift, and why memcpy (which doesn't handle overlaps) would be wrong here.

🎯 Remember this: Insertion = shift right from the end backward, then write the value, then increment the length. Working backward avoids overwriting elements before they've been copied. The valid positions are 0 through *n inclusive; pos = 0 inserts at the front (O(n) shifts), pos = *n appends at the end (O(1) — no shifts). The length must be passed by int * because the function can only return one value.

Frequently Asked Questions

1. Why must the shift go backward?

Because shifting right while walking forward would overwrite elements before they've been copied. Consider shifting [10, 20, 40, 50] right starting at index 2: if you copy arr[2] into arr[3] first, you lose the original arr[3] (40). The next iteration copies the new arr[3] (also 40, since it was just overwritten) into arr[4], producing duplicates instead of a shift. Working backward — copy arr[3] into arr[4], then arr[2] into arr[3] — each source is read before its slot is overwritten, so the original values are preserved. The rule is: when the source and destination ranges overlap, walk in the direction that reads before writing. For right shifts, that's backward.

2. Why is pos == *n a valid position?

Because inserting at position *n appends to the end — there are *n existing elements at indices 0 through *n - 1, and inserting at *n puts the new value after all of them, with no shift needed. The valid range is 0 <= pos <= *n. If you rejected pos == *n, you'd be unable to append efficiently. The loop's condition handles this automatically: for pos == *n, dst == arr + pos from the start, so the loop doesn't run, and the write goes directly to arr[*n] — the new last slot. O(1) — append is always O(1).

3. Why check for a full array?

Because inserting into a full array would write past the end of the buffer, which is undefined behaviour — often silent memory corruption, sometimes a crash. The check *n >= MAX catches this before any write happens. If the array were dynamically allocated, you could instead grow it with realloc and continue the insert — but the static MAX array has a fixed capacity, so the only option is to reject. Production code should always check capacity before inserting. This is one of the most common sources of buffer-overflow bugs in C.

4. Why does the function take the length by pointer?

Because the length changes during the operation, and the caller needs to know the new length. C functions can only return one value, so the modified array (delivered in place) and the new length (delivered through int *n) can't both come from the return slot. Passing &n lets the function write the new length to the caller's variable. This is symmetric with the delete function — both change the size of the array, so both take int *n. Passing by pointer is the standard C idiom for "functions that modify their arguments in place," and it's used everywhere in the standard library (consider fread(&buf, ...) or scanf("%d", &x)).

5. Why not use memmove instead of a loop?

In production code, you would use memmove — it's shorter, faster (often SIMD-accelerated), and handles overlapping ranges correctly. But the assignment asks for a pointer-based solution, and writing the loop teaches you what memmove actually does: it copies a range of elements and must walk in the right direction (for right shifts, backward) to avoid clobbering source bytes before they're read. After writing the loop, you understand why memmove is the right function for this operation, and why memcpy (which doesn't handle overlaps) would be wrong. Both are worth knowing; the loop is the teaching version.

6. What is the time and space complexity?

Time is O(n - pos) — O(n) in the worst case (insert at index 0, shift all n elements) and O(1) in the best case (append at the end, no shift). Space is O(1): a few local pointers and the value parameter. This is optimal for an array insertion: you can't insert into the middle without moving the elements after it, and moving them takes O(n) time in the worst case. The only way to do better asymptotically is a linked list (O(1) insertion once you have a pointer, but O(n) search) — a trade-off worth knowing.

💡 Tip: Once this works, try the mirror operation: delete an element at a given position. That's the previous assignment (#25), and the shift goes the other way — from arr + pos + 1 forward to arr + *n — with the length decremented instead of incremented. Seeing both side by side is the best way to consolidate the pointer range-shift pattern and the "shift direction depends on which side you're opening/closing" rule.

📖 Related Tutorials

  • 25. Delete an Element from an Array Using Pointers
  • 26. Sum of Digits of a Number Using Pointers
  • 4. Reverse an Array Using Pointers
  • 18. Sort an Array Using a Function and Pointers
  • 16. Find the Maximum Element in an Array Using Pointers
  • All 30 Pointer Assignments

Previous Topic: -->> 18. Sort an Array Using a Function and Pointers   ||   Next Topic: -->> 25. Delete an Element from 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.