简体   繁体   English

在C ++中将结构复制到数组中

[英]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. 第28行是发生memcpy的行。 Any help appreciated. 任何帮助表示赞赏。

You don't need to use malloc or memcpy at all. 您根本不需要使用mallocmemcpy 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的第一个参数需要一个指针,而第三个参数需要的是struct的大小, 而不是指针的大小。

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. 您不能以定义的方式使用memcpy复制结构。 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. ie drop the cast on the right hand side. It's unnecessary in C.) (有一小点,写Edge* e = malloc(sizeof(Edge));相反。即,将演员表放在右侧。在C语言中是不必要的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM