Copying a struct into an array in C++

I've a struct of the following type

typedef struct Edge
    int first;
    int second;


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/ error: no suitable conversion function from "Edge" to "void *" exists  

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


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

Need Your Help

Jackson JsonMappingException: Can not deserialize instance of class out of START_ARRAY token

android arrays json jackson

Unable to read value of image arr. How can I read the value of Image arr using jackson json mapper .

Spring too high memory usage

java spring hibernate spring-mvc memory-leaks

I have a webapp that combines Spring + Hibernate. I deploy this locally in a Tomcat Server and I get memory consumptions of around 150-200 Mb which to my knowledge is not that high at all. But appa...