How to copy part of an array from 2d array to 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 'to' so that 'in' = {1, 2, 3}

I am trying to do this using memcpy (I know that it already works with the loop), but I cannot get it to work.

I keep getting the error:

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

I found a link to this question:

How to 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 still don’t know, I solved my problem differently, but curiosity I would like to know how this is done, as from the previous post, I know that this is possible.

+4
source share
2 answers

As KingsIndian points out, you can avoid the problem by dropping the assignment, since you really don't need the return value in this instance. However, this may help the future understand what is happening under the hood:

memcpy returns a pointer to destination. If "in" was a pointer, then that would be nice:

 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 the β€œin” is an array, not a pointer. Arrays in C are not variables, that is, they cannot be assigned, therefore, an error. Although he often said that arrays and pointers are equivalent, there are differences, and this is one thing. For more information on the differences between arrays and pointers, see here:

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

Edit:

To avoid the problem at all, without completing any tasks, ignore the return value:

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

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

  #include <string.h> void *memcpy(void *dest, const void *src, size_t n); 

What you might want:

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

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

+2
source

Source: https://habr.com/ru/post/1483029/


All Articles