1

I have a dynamic array of integers:

int *array = malloc(1000 * sizeof(int));
for (int i = 0; i < 1000; ++i) {
    array[i] = i;
}

How can I effectively delete elements between 555-565 without creating new array and copying elements there?

7
  • Copy 0-554 and 566-999 to a new array of 990 elements... Then free the old array. Commented Sep 8, 2016 at 15:25
  • 1
    You can't! You can just move entries above to the range. Commented Sep 8, 2016 at 15:25
  • 1
    @LPs: That would not delete the elements, but create a new array. Commented Sep 8, 2016 at 15:25
  • @Olaf Well, it was a joke. Commented Sep 8, 2016 at 15:26
  • This has nothing to do with the array being dynamically allocated. Commented Sep 8, 2016 at 15:31

2 Answers 2

2

Could this be accounted as a deletion?

#include <stdio.h>
#include <malloc.h>
#include <string.h>

int main(void) {
int* array = malloc(sizeof(int)*110);

for(int i=0; i<100; i++) 
          array[i]=i;

for (int r=56; r<100; r++)
        array[r]=array[r+6];

//memset(array+94, 0, 5);
memset(array+94, 0, 5 * sizeof(int));

}
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it the following way

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() 
{
    size_t N = 1000;
    int *a = malloc( N * sizeof( int ) );

    for ( size_t i = 0; i < N; ++i ) a[i] = i;

    size_t n1 = 555, n2 = 565;


    for ( size_t i = n1; i < n2 + 1; i++ ) printf( "%d ", a[i] );
    printf( "\n" );

    memmove( a + n1, a + n2, ( N - n2 ) * sizeof( int ) );

    int *tmp = realloc( a, ( N - n2 + n1 ) * sizeof( int ) );

    if ( tmp ) a = tmp;

    for ( size_t i = n1; i < n2 + 1; i++ ) printf( "%d ", a[i] );
    printf( "\n" );

    free( a );
}

The program output is

555 556 557 558 559 560 561 562 563 564 565 
565 566 567 568 569 570 571 572 573 574 565 

Or you can avoid the array reallocation simply by supporting the current number of actual elements in the array.

7 Comments

at memmove and realloc , It is not correct size.
@BLUEPIXY Thanks. It is a typo.:)
It still have typo.
@BLUEPIXY I think that now the program does not have a typo.:)
@RomaKarageorgievich: Vlad is making sure the realloc call succeeded by checking the value of tmp; if it's not NULL, then the buffer was properly resized, and the (potentially) new buffer pointer is then assigned back to a. If he had assigned the result directly back to a without checking and the realloc call had failed, then he would have lost his only reference to the previously-allocated memory.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.