Removal Using memcpy in an array

Given the index and the array of integers, I need to remove the element in the given array that was stored in this index with memcpy(). A new set of elements will be stored in this array.

Here is an illustration of what I want to do, although I have problems with its implementation.

enter image description here

So, arrayElemafter removing 10 it will look like this:

enter image description here

+4
source share
4 answers

You cannot use memcpy as the source and destination overlap, but you can use memmove , for example:

memmove(&a[1], &a[2], 5 * sizeof(a[0]));

5 , a[2] 5 , a[1], , .

+4

memcpy() . memmove().

memcpy()

memcpy() n src dest. . memmove(3), .

: memmove()

, , 2- , memcpy(),

  • memcpy()
  • memcpy() , .

FWIW, 6. . .

+1

memcpy, . undefined.

memmove.

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

size_t remove_by_index( int a[], size_t n, size_t i )
{
    if ( i < n )
    {
        memmove( a + i, a + i + 1, ( n - i - 1 ) * sizeof( *a ) );
        --n;
    }

    return n;
}

int main( void ) 
{
    int a[] = { 1, 10, 5, 8, 4, 51, 2 };
    const size_t N = sizeof( a ) / sizeof( *a );
    size_t n = N;

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

    n = remove_by_index( a, n, 1 );

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

    return 0;
}

1 10 5 8 4 51 2 
1 5 8 4 51 2 
+1

"" memcpy, 1 , . memcpy , , .

for(int i=1; i<=5; i++)
{
    memcpy(arrayElem[i], arrayElem[i+1], sizeof(*arrayElem));
}

Icky, , . memmove 100% .

+1

All Articles