# Copying a struct into an array in C++

I've a struct of the following type

typedef struct Edge { int first; int second; }Edge;

Which I'm instantiating in my main function and copying into an array

Edge h_edges[NUM_EDGES]; for (int i = 0; i < NUM_VERTICES; ++i) { Edge* e = (Edge*)malloc(sizeof(Edge)); e->first = (rand() % (NUM_VERTICES+1)); e->second = (rand() % (NUM_VERTICES+1)); memcpy(h_edges[i], e, sizeof(e)); }

I keep running into the following error.

src/main.cu(28): error: no suitable conversion function from "Edge" to "void *" exists

Line 28 is the line where the memcpy happens. Any help appreciated.

## Answers

You don't need to use malloc or memcpy at all. You can just:

Edge h_edges[NUM_EDGES]; for (int i = 0; i < NUM_VERTICES; ++i) // or should this be NUM_EDGES?? { h_edges[i].first = (rand() % (NUM_VERTICES+1)); h_edges[i].second = (rand() % (NUM_VERTICES+1)); }

The first parameter of memcpy takes a pointer and the third argument needs to the size of the struct, **not** the pointer.

memcpy(&h_edges[i], e, sizeof(*e));

is the fix.

But this is ill-advised. Strictly the behaviour of your program is *undefined*. You can't copy a structure using memcpy in a defined way. Essentially the reason for this lies in structure packing.

Your best bet is to copy the structure members explicitly. You could build a function to do that.

An other point is that using % will introduce statistical bias in your random numbers, unless the modulus is a multiple of the generator's periodicity; which is unlikely.

(A small point, write Edge* e = malloc(sizeof(Edge)); instead. i.e. drop the cast on the right hand side. It's unnecessary in C.)