Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deletion Using memcpy in an array

Tags:

arrays

c

memcpy

Given an index and an array of integers, I need to delete the element in the given array which was stored in the given index through the use of memcpy(). The new set of elements will be stored on the given array.

Here's an illustration of what I want to do, though I'm having trouble implementing it.

enter image description here

So arrayElem after deleting 10 would look like this:

enter image description here

like image 877
KaelJasper Avatar asked Jul 09 '15 14:07

KaelJasper


People also ask

How to delete an element from an array?

To delete a specific element from an array, a user must define the position from which the array's element should be removed. The deletion of the element does not affect the size of an array. Furthermore, we should also check whether the deletion is possible or not in an array.

Does memcpy work with arrays?

Memcpy copies data bytes by byte from the source array to the destination array. This copying of data is threadsafe. The process of copying data can fail if the given size is not accurate for the destination array.

Does memcpy clear memory?

memcpy() itself doesn't do any memory allocations. You delete what you new , and delete[] what you new[] . You do neither new nor new[] . Both source and destination arrays are allocated on the stack and will be automatically deallocated when then go out of scope.


2 Answers

You can't use memcpy, because source and destination overlap, but you can use memmove, e.g.:

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

This copies the 5 elements starting at a[2] down to the 5 elements starting at a[1], taking care of the fact that the source and destination regions overlap.

like image 187
Paul R Avatar answered Sep 30 '22 05:09

Paul R


You may not use function memcpy because the ranges of the array overlap each other. In this case the behaviour will be undefined.

Instead you have to use standard function memmove.

Here is a demonstrative program

#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;
}

The program output is

1 10 5 8 4 51 2 
1 5 8 4 51 2 
like image 35
Vlad from Moscow Avatar answered Sep 30 '22 06:09

Vlad from Moscow