Search code examples
carraysmultidimensional-arraymemcpy

How to copy part of an array from a 2d array into another array in C


So I have the following:

int from[2][3] = { {1,2,3}, {2,3,4} };
int into[3];

into = memcpy(into, from[0], 3 * sizeof(*into));

I want to copy 'from' in to the array 'into' so that 'into' = { 1, 2, 3}

I am trying to do the above using memcpy (i know that it already works with a loop) but I cant seem to get it working.

I keep on getting the error :

error: incompatible types when assigning to type ‘int[3]’ from type ‘void *’

I found a link to this question:

How do I copy a one-dimensional array to part of another two-dimensional array, and vice-versa?

and changed my code (Above) but i still get the error.

I am still clueless, I have solved my problem in another manner but curiosity I would like to know how it is done as from the previous post I know it is possible.


Solution

  • As KingsIndian points out, you can avoid the problem by dropping the assignment, since you don't actually need the return value in this instance. However it may help for the future to understand what's going on under the hood:

    memcpy returns a pointer to its destination. If "into" were a pointer, then it would be fine:

    int from[2][3] = { {1,2,3}, {2,3,4} };
    int into[3];
    int *into_ptr = into;
    
    into_ptr = memcpy(into_ptr, from[0], 3 * sizeof(int)); // OK
    

    The problem is that "into" is an array, not a pointer. Arrays in C are not variables, i.e. they cannot be assigned to, hence the error. Although it's often said that arrays and pointers are equivalent, there are differences, this being one. More detail on the differences between arrays and pointers is given here:

    http://eli.thegreenplace.net/2009/10/21/are-pointers-and-arrays-equivalent-in-c/

    Edit:

    To avoid the problem altogether by not doing any assignment, ignore the return value:

    int from[2][3] = { {1,2,3}, {2,3,4} };
    int into[3];
    
    memcpy(&into[0], from[0], sizeof(into));