Search code examples
c++arraysconcatenationmemcpymemmove

memcpy or memmove between different arrays


I was reading some information about memcpy and memmove, and if I'm not wrong, you can use both for move memory between different arrays.

So here is my question: If I want to concatenate this objects with this method.

class List
{
    // Pointer to the beginning.
    int* vector;

    // Number of elements, n >= 0
    int n;

    // Capacity for new elements.
    int capacity;
}

void concatenateList(List* listToConcatenate)
{    
    memmove(this->vector + n, listToConcatenate->vector, (listToConcatenate->n)*sizeof(int));
}

So, from "listToConcatenate->vector" which is the beggining, we will copy all elements from it with "(listToConcatenate->n)*sizeof(int))", and we will put it at the end of the other array "this->vector + n".

Shouldn't this be correct list2.listToConcatenate(&list1);? Assuming, of course, we got enough space.

If it is not, what would be the right way to do it? Could this be done with memcpy?

Thank you.

Edit: I think I need to add that this does not work on my program. It doesn't crash, but seems like it does nothing.


Solution

  • Ok, I found my mistake.

    Yes, you can do that with memmove but I missed something:

    void concatenateList(List* listToConcatenate)
    {    
        memmove(this->vector + n, listToConcatenate->vector, (listToConcatenate->n)*sizeof(int));
        this->n += listToConcatenate->n; //Mistake here.
    };
    

    That's why it wasn't printing anything. But yeah, I have memmove a bit clearer now. Thank you all for your answers.