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?
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));
}
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.
memmove and realloc , It is not correct size.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.
0-554and566-999to a new array of990elements... Then free the old array.