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,994 questions

51,939 answers

573 users

How to delete an element from dynamic array in C

1 Answer

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

int main(void)
{
    int *p, *tmp, i, j, size, pos;
    
    printf("Enter array size: ");
    scanf("%d", &size);
    
    p = malloc(size * sizeof(int));
    if (p == NULL) 
    {
        printf("Error allocating memory\n"); 
        return 1;
    }
    
    srand(time(NULL)); 
    for (i = 0; i < size; i++)
    {
         p[i] = rand() % 100 + 1;
         printf("arr[%d] = %d\n", i, p[i]);
    }
    
    pos = 2; // delete the element in this position
    
    tmp = malloc((size - 1) * sizeof(int));
    if (tmp != NULL) 
    {
        for (i = 0, j = 0; i < size; i++)
        {
             if (i != pos)
                 tmp[j++] = p[i];
        }
        free(p);
        p = tmp;
        size--;
    }
    else 
    {
        free(tmp);
        printf("Error allocating memory!\n");
        return 1;
    }  
   
    printf("after delete:\n");
    for (i = 0; i < size; i++)
         printf("arr[%d] = %d\n", i, p[i]);
    
    free(p);
 
    return 0;
}
/*
run:
Enter array size: 5
arr[0] = 8
arr[1] = 11
arr[2] = 80
arr[3] = 49
arr[4] = 15
after delete:
arr[0] = 8
arr[1] = 11
arr[2] = 49
arr[3] = 15
*/



answered Sep 13, 2014 by avibootz
edited Sep 22, 2014 by avibootz

Related questions

...