如何在C ++中连接两个结构类型变量? [英] How can I concatenate two structs type variables in c++?

查看:79
本文介绍了如何在C ++中连接两个结构类型变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将一些struct(我定义的)类型变量连接成一个更大的变量.我得到的基本上是这样的:

I'e been trying for sometime to concatenate some struct (I defined) type variables into a bigger one. What I got is basically like this:

我有一个结构和两个类型为struct **的变量. 我声明了第三个结构C,我想将A和B连接到C中. 我试过的是这样的事情(我现在没有代码在我面前,所以我写的东西很相似,但是我不记得他们的名字了.

I have a struct and two variables of type struct**. I declare a third one struct C and I want to concatenate A and B into C. What I tried is something like this (I don't have the code in front of me right now so I'll write something very similar with some names changed as I don't remember them.

struct** A, B;
struct** C;

(我知道A和B是通过调用另一个函数来接收的)

(I know A and B as I receive them by calling another function)

我像这样为C分配内存.

I allocate memory for C like this.

C = (struct**)malloc(sizeof(A)+sizeof(B));

我像这样用memcpy移动A和B.

And I move A and B with memcpy like this.

memcpy(&C, &A, sizeof(A));
memcpy(&C + sizeof(A), &C, sizeof(B));

很明显,我所做的不正确,因为在所有C中仅包含A. 我很确定问题出在"**",我不能很好地处理指向指针的指针. 有人可以给我一些有关我的问题的建议吗? 我也不想使用Handles,我必须使用memcpy/memmove.

It's obvious that what I've done is not correct as it seems after all of this C contains only A. I'm pretty sure the problem is from "**", I can't handle pointers to pointers that well. Can anybody give me some advice regarding my issue? I also don't want to use Handles, I have to use memcpy/memmove.

[评论更新:]

我的结构都是相同的类型.

My struct are all the same type.

推荐答案

您已经在某处定义了struct A a;struct B b;. 要将它们连接为struct C,请执行以下操作:

You already have a struct A a; and a struct B b; defined somewhere. To concatenate them into a struct C you do this:

struct A a;
struct B b;

struct C{
    struct A a;
    struct B b;
};

struct C c;
c.a = a;
c.b = b;

不需要指针或memcpy.

由于ab是同一类型,因此您可以将其略为缩短:

Since a and b are of the same type you can somewhat shorten it to this:

struct Something a, b;

struct C{
    struct Something[2];
};

struct C c;
c[0] = a;
c[1] = b;

在C ++中,您将执行以下操作:

In C++ you would do something like this:

using C = std::array<Something, 2>;
C c{a, b};

这篇关于如何在C ++中连接两个结构类型变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆