cxzp
cxzp

Reputation: 672

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.

Upvotes: 4

Views: 6901

Answers (2)

Stefan
Stefan

Reputation: 9329

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));

Upvotes: 3

P.P
P.P

Reputation: 121377

memcpy returns a pointer to the destination which you are trying to assign to an array. You can ignore the return value of memcpy.

   #include <string.h>

   void *memcpy(void *dest, const void *src, size_t n);

What you probably want is:

memcpy(into, from[0], sizeof into);

This will copy the 3 elements of 4 bytes each ( sizeof into == 12 here) from from[0] to into.

Upvotes: 2

Related Questions