Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to remove an element at a specific index from a dynamic array in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

#define STARTSIZE 6

void removeElement(int* array, int size, int index) {
    if (index < 0 || index >= size) {
        printf("Index out of bounds\n");
        return;
    }

    for (int i = index; i < size - 1; i++) {
        array[i] = array[i + 1];
    }
    
    // Optionally, resize the array if needed
    array = realloc(array, (size - 1) * sizeof(int));
}

int main() {
    int size = STARTSIZE;
    int* array = (int*)malloc(size * sizeof(int));
    
    if (array == NULL) {
        puts("malloc() error");
        return -1;
    }

    // Initialize the array
    for (int i = 0; i < size; i++) {
        array[i] = ((i + size) * size) / (i + 1);
    }
    
    printf("Original array:      ");
    for (int i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    int indexToRemove = 2; 

    removeElement(array, size, indexToRemove);
    size--; // Decrease the size after removal

    printf("Array after removal: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }

    free(array);
    
    return 0;
}


  
/*
run:
  
Original array:      36 21 16 13 12 11 
Array after removal: 36 21 13 12 11 
  
*/

 



answered Feb 20, 2025 by avibootz
edited Feb 20, 2025 by avibootz

Related questions

1 answer 73 views
1 answer 76 views
1 answer 141 views
2 answers 262 views
1 answer 179 views
2 answers 197 views
1 answer 153 views
...