Pointer Assignment 25 — Delete an Element from an Array Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Delete an Element from an Array Using Pointers — Shifting Left Through a Pointer Pair

📑 On this page:
  • How Pointer-Based Array Deletion Works
  • The Three Steps of the Deletion
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to delete an array element by shifting subsequent elements left
  • How to use two pointers (src and dst) to express a shift compactly
  • Why the length must be passed back to the caller — int arrays don't carry their size
  • How to validate the position and handle edge cases (first, last, invalid)
  • The difference between deleting and "zeroing out" — why the last slot becomes garbage

How Pointer-Based Array Deletion Works

Deleting an element from an array at a given position means removing the value that sits there and closing the gap it leaves behind. In an array, "closing the gap" means shifting every subsequent element one position to the left. After the shift, the element that was at index pos + 1 is now at pos, the element at pos + 2 is at pos + 1, and so on, with the last element moving one slot left. The array's length decreases by one, and the old last slot becomes unused (or "garbage").

Doing this with pointers is a natural fit. You can think of the operation as copying the range [arr + pos + 1, arr + n) into the range starting at arr + pos. That's exactly what memmove does, and it's exactly what two pointers do when you advance them in lockstep. Let dst = arr + pos and src = arr + pos + 1. On each iteration, *dst = *src copies the source into the destination, then dst++ and src++ move both forward. When src reaches arr + n, the shift is complete.

The length is not part of the array — it's bookkeeping that the caller owns. C arrays don't carry their size, so the function must either return the new length, or take a pointer to the length and update it. In this program, the function takes int *n, decrements *n after shifting, and writes the new length back. The caller sees both the modified array and the updated length. Passing the length by pointer is the standard pattern for any operation that changes the size of an array, because it's the only way for a function to communicate the new size to the caller without using the return value.

💡 In one line: Set dst = arr + pos and src = dst + 1, then copy *src into *dst while advancing both until src reaches arr + n, and finally decrement *n.

Diagram showing two pointers src and dst walking left over an array, copying src into dst to shift all elements one position left after a deletion

The Three Steps of the Deletion

Step Pointer operation Effect
1. Validateif (arr == NULL || pos < 0 || pos >= *n) return -1;Reject impossible deletions early
2. Shift leftfor (int *dst = arr + pos, *src = dst + 1; src < arr + *n; dst++, src++) *dst = *src;Every element after pos moves one slot left
3. Shrink(*n)--;The array now has one fewer valid element

The shift loop is the core. Its condition src < arr + *n uses the current length, before the decrement. That's correct — you want to copy all the elements that are currently valid, including the last one, into the slot before it. After the loop, the last slot still contains a copy of the last element (because dst was at arr + *n - 2 when it received the value from src = arr + *n - 1), and then (*n)-- makes that slot "outside" the valid array. It's garbage from the caller's perspective — they shouldn't read it — but it's still in the buffer until overwritten.

The loop could be written with an index version just as easily: for (int j = pos; j < *n - 1; j++) arr[j] = arr[j + 1];. The pointer version and the index version do the same thing, because arr[j] is defined as *(arr + j). The pointer version has the advantage of making the "source" and "destination" ranges explicit — you can see at a glance that one pointer follows the other. But the index version is arguably more readable for beginners. Both are correct, and both are O(n) time with O(1) extra space.

Complete C Program

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

#include <stdio.h>

#define MAX 100

/* Delete the element at index pos from arr.
   Returns 0 on success, -1 if pos is out of range.
   The new length is written back through n. */
int delete_at(int *arr, int *n, int pos) {
    if (arr == NULL || n == NULL || *n <= 0 || pos < 0 || pos >= *n) {
        return -1;
    }

    /* Shift every element after pos one slot to the left. */
    int *dst = arr + pos;
    int *src = dst + 1;
    int *end = arr + *n;

    while (src < end) {
        *dst = *src;
        dst++;
        src++;
    }

    /* One fewer valid element. */
    (*n)--;

    /* Optional: clear the now-unused last slot, for tidiness. */
    arr[*n] = 0;

    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, 30, 40, 50, 60};
    int n = 6;

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

    int pos = 2;    /* delete the element at index 2 (30) */
    if (delete_at(arr, &n, pos) == 0) {
        printf("After deleting index %d: ", pos);
        print_array(arr, n);
    } else {
        printf("Delete failed: position %d is out of range.\n", pos);
    }

    /* Edge case: delete the first element */
    if (delete_at(arr, &n, 0) == 0) {
        printf("After deleting index 0: ");
        print_array(arr, n);
    }

    /* Edge case: delete the last element */
    if (delete_at(arr, &n, n - 1) == 0) {
        printf("After deleting last  : ");
        print_array(arr, n);
    }

    /* Edge case: invalid position */
    if (delete_at(arr, &n, 100) != 0) {
        printf("Delete at index 100 failed (out of range).\n");
    }

    return 0;
}
                                    

Program Output

Before: [10, 20, 30, 40, 50, 60]
After deleting index 2: [10, 20, 40, 50, 60]
After deleting index 0: [20, 40, 50, 60]
After deleting last  : [20, 40, 50]
Delete at index 100 failed (out of range).
                                

The output walks through the four cases. First, the array starts with six elements and index 2 is deleted; the array shifts left and the 30 disappears. Then index 0 is deleted; the array shifts left again, removing 10. Then the last element is deleted; the array shifts left and the 50 is removed. Finally, an out-of-range delete is attempted and rejected — the array is unchanged. The parentheses around the array in the output help show the shifting visually: after each deletion, exactly one fewer element appears, and the elements are in the same relative order.

Step-by-Step Explanation

Let's walk through the pointer and length mechanics.

1. The function signature

int delete_at(int *arr, int *n, int pos) takes three 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 to delete. The return value is int, signalling success (0) or failure (-1) — a common C convention where 0 means success and any non-zero means an error.

2. Validation

if (arr == NULL || n == NULL || *n <= 0 || pos < 0 || pos >= *n) return -1; checks everything that could go wrong. A null array or null length pointer means the caller made a mistake. An empty array has nothing to delete. A negative pos is out of range. A pos at or beyond *n is also out of range. All of these are caught before any writes happen, so the caller's array is untouched on failure. This is important: a function that modifies data should validate before it modifies.

3. Setting up the pointer pair

int *dst = arr + pos; points at the element to delete — the slot that will be overwritten by the next element. int *src = dst + 1; points at the element that will move into dst's slot. int *end = arr + *n; is one past the last valid element — the loop's upper bound. Using *n rather than n is essential: n is a pointer to the length, and the length is the value *n.

4. The shift loop

while (src < end) { *dst = *src; dst++; src++; } is the core. Each iteration copies the value at src into the slot at dst, then moves both pointers forward. After the first iteration, the element that was at pos + 1 is now at pos. After the second, the element that was at pos + 2 is at pos + 1. And so on. When src reaches end, every element from pos + 1 to *n - 1 has been copied one slot to the left. The original element at pos has been overwritten and is gone — it's been "deleted."

5. Why *dst = *src and not *dst = *(src + 1)

This is a common place to get confused. The key is that src is initialised as dst + 1, so *src is already "the element after dst." Writing *dst = *src copies the next element into the current slot. Writing *dst = *(src + 1) would copy two elements ahead, skipping one — a bug. The pattern is simpler if you think of dst as "where I'm writing" and src as "where I'm reading from." Each step moves both one slot right, so src always trails dst by exactly one position.

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

n = 6, dst = arr + 2 (points at 30), src = arr + 3 (points at 40), end = arr + 6.

  • Iteration 1: *dst = *src → arr[2] = 40. Array becomes [10, 20, 40, 40, 50, 60]. dst → index 3, src → index 4.
  • Iteration 2: arr[3] = 50. Array becomes [10, 20, 40, 50, 50, 60]. dst → 4, src → 5.
  • Iteration 3: arr[4] = 60. Array becomes [10, 20, 40, 50, 60, 60]. dst → 5, src → 6.
  • src == end, loop exits.

Now (*n)-- sets n = 5. The valid elements are [10, 20, 40, 50, 60] — indices 0 to 4. The trailing 60 at index 5 is now garbage and the program clears it to 0 for tidiness.

7. Deleting the first element

With pos = 0, dst = arr and src = arr + 1. The loop copies every subsequent element one slot to the left: arr[0] = arr[1], arr[1] = arr[2], and so on. After the loop, the array has shifted left by one, and (*n)-- reduces the length. This works correctly — the "delete the first element" case is handled by the same code as any other position, with no special-casing.

8. Deleting the last element

With pos = n - 1, dst = arr + n - 1 and src = arr + n. But end = arr + n, so the loop condition src < end is immediately false. The loop body never runs, and the only effect is (*n)-- — the length shrinks by one. The element at the old last position is now "outside" the valid array, so it's effectively deleted without needing to move anything. This is correct and efficient: deleting the last element is O(1), not O(n).

9. Why the last slot becomes garbage

After the shift, the last valid slot (arr[*n]) still contains the value that was previously at arr[*n - 1] — a leftover from the copy. It's not part of the valid array (because n was decremented), but it's still in the buffer. The program clears it with arr[*n] = 0 for tidiness and for easier debugging — if you print the whole buffer, you can see where the "active" region ends. In production code, this cleanup is optional but often worth doing, especially if the array might be passed elsewhere with a wrong length by mistake.

10. Why the length is passed by pointer

The function needs to communicate two results: the modified array (delivered in place) and the new length (delivered through the pointer). C functions can only return one value, so the length has to come out through a pointer. This is the standard idiom for any operation that changes an array's size — insertion, deletion, filtering, sorting that removes duplicates. If you didn't pass &n, the caller would have to decrement its own n after calling — which is error-prone (easy to forget) and couples the caller to the function's internals. Passing the length by pointer makes the function self-contained.

11. Complexity

The shift loop runs from src = arr + pos + 1 to src = arr + *n, which is (*n) - pos - 1 iterations. In the worst case — deleting the first element of an n-element array — that's n - 1 iterations, so time is O(n). In the best case — deleting the last element — it's 0 iterations, so O(1). Space is O(1): only a few local pointers. This is optimal for an array-based deletion: there's no way to delete from the middle without moving the elements after the deletion point, and O(n) moves is the best you can do.

12. Why use memmove instead of a loop?

The standard library provides memmove(dst, src, bytes), which copies a block of memory and correctly handles overlapping regions. The array shift in this program is exactly the kind of overlapping copy that memmove is designed for. Here's how it would look:

#include <string.h>
memmove(arr + pos, arr + pos + 1, (*n - pos - 1) * sizeof(int));
(*n)--;
                                

This is shorter, likely faster (because memmove can use SIMD or other optimisations), and less error-prone than a hand-written loop. In production code, memmove is the right choice. But for a pointer-arithmetic exercise, the hand-written loop teaches you what memmove does under the hood — and that's the point of this assignment. After you've written the loop, you understand the range semantics of memmove at a much deeper level.

🎯 Remember this: Deleting an element means shifting the elements after it one slot to the left, then decreasing the length. Two pointers (dst at the deletion point, src one past it) express the shift compactly. The length is passed by int * so the function can update it. This is O(n) time, O(1) space, and deleting the last element is O(1) because no shift is needed.

Frequently Asked Questions

1. 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, so the caller sees both changes. This is the standard C idiom for any function that changes an array's size.

2. Why is the last element's slot still populated after deletion?

Because the shift loop copies elements one slot left, and the last assignment copies the second-to-last element into the last slot. The value at the original last position is copied to the slot before it, then the length is decremented, so the original last slot is no longer part of the "valid" array. But it's still in the buffer until overwritten — it's "garbage" from the caller's perspective. The program optionally clears it with arr[*n] = 0 to make debugging easier (so you can see where the active region ends). In production code, this cleanup is optional.

3. What happens if I pass a position out of range?

The function returns -1 and does nothing to the array. The validation if (pos < 0 || pos >= *n) return -1; catches both negative positions and positions at or beyond the end. Without this guard, the shift loop would start at arr + pos, which could be outside the array — undefined behaviour, often a crash or silent corruption. The guard is essential for a robust function; a library routine that's called with untrusted input must always validate.

4. Can I delete multiple elements at once?

Yes, but you need to be careful about the indices. If you're deleting elements at several positions, delete them from highest to lowest index — that way, earlier deletions don't invalidate the positions of elements you haven't deleted yet. Deleting from lowest to highest shifts later elements down by one, so the original positions no longer point at the intended elements. If you need to delete a set of positions, you can also do it in one pass by filtering (copy elements that aren't in the delete set into a new position, incrementing a write pointer), which is O(n) instead of O(k·n).

5. Why not use memmove instead of a loop?

In production code, you would use memmove(arr + pos, arr + pos + 1, (*n - pos - 1) * sizeof(int)) — it's shorter, faster (implementations often use SIMD), 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 from one region to another, and if the regions overlap, it must copy in the right direction to avoid clobbering source bytes before they're read. The hand-written loop makes that visible; the library call hides it. Both are correct for this problem, and knowing both is useful.

6. What is the time and space complexity?

Time is O(n) in the worst case (deleting the first element shifts n - 1 elements) and O(1) in the best case (deleting the last element shifts nothing). Space is O(1) — a few local pointers. This is optimal for an array deletion: you can't remove an element from 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 different data structure (like a linked list, where deletion is O(1) once you have a pointer to the element, at the cost of O(n) search), which is a trade-off worth knowing.

💡 Tip: Once this works, try the mirror operation: insert an element at a given position. The loop goes the other direction — from the end backward — to make room for the new element. Insertion and deletion are exact opposites in terms of the shift direction and the length change. Seeing both side by side is the best way to consolidate the pointer range-shift pattern.

📖 Related Tutorials

  • 24. Insert an Element into 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: -->> 24. Insert an Element into an Array Using Pointers   ||   Next Topic: -->> 26. Sum of Digits of a Number 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.