c++ - 将结构的动态数组复制到另一个结构

标签 c++ arrays struct

我有一个这样定义的结构:

struct Queries {

    uint64_t Id;
    uint64_t from;  
    uint32_t counter; // total queries
    char queries[];
};

我想做的是创建一个新的结构“对象”,并将现有结构的值复制到这个新对象。

我尝试过的

void function(Queries* oldq){

    Queries* q = new Queries();

    // values are copied correctly
    q->Id = oldq->Id;
    q->from = oldq->from;
    q->counter = oldq->counter;

    // copy is not correct
    for (unsinged i = 0; i < oldq->counter; i++)
          q->queries[i] = oldq->queries[i];

}

1)我也试过:

q = oldq;

但这行不通。

2) 我想我必须为查询数组分配 counter * sizeof(char) 空间,但由于结构的成员不是指针,我不知道该怎么做。

最佳答案

这里你正在处理一个 C-style flexible array member .它不是有效的 C++ 代码,但自 C99 以来它是有效的 C(有关详细信息,请参见链接)。要使用这样的结构,您需要分配 sizeof(Queries) + counter 字节,其中数组字段将使用 counter 字节部分。 (注意:如果您有 char 以外的数组字段,则必须相应地相乘。)

现在,您不能在这里使用 C++ 功能,例如复制构造函数,因为编译器不知道您的结构的大小。相反,您必须使用纯 C 方法:

Queries *cloneQueries(Queries *oldQ)
{
    size_t sizeQ = sizeof(Queries) + oldQ->counter;
    Queries *newQ = (Queries*)malloc(sizeQ);
    memcpy(newQ, oldQ, sizeQ);
    return newQ;
}

关于c++ - 将结构的动态数组复制到另一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34680992/

相关文章:

C++ 指向 vector 行为的指针

c++ - 以编程方式求解方程组?

ruby - XML解析元素和元素属性到数组中

c - 缩短 struct *pointerexample 以便我不必输入它的方法?

c++ - 成员函数中 'delete this' 的用处

c++ - 为什么循环给出的结果与累积的结果不同?

arrays - 如何在 VBA 中粘贴整个数组而不循环遍历它?

javascript - 如何在 JavaScript 中为对象值添加标签

c - 结构的字段是否算作变量?数组的元素算作变量吗?

c - 在链接列表中对空指针进行类型转换