【问题标题】:How to use struct within an union, within a struct in C?如何在联合中使用结构,在 C 中的结构内?
【发布时间】:2014-06-10 09:29:51
【问题描述】:

我目前在与一个对我个人而言非常复杂的结构进行了很多斗争

struct crypto_tfm
{
    uint32_t crt_flags;

    union
    {
        struct ablkcipher_tfm ablkcipher;
        struct aead_tfm aead;
        struct blkcipher_tfm blkcipher;
        struct cipher_tfm cipher;
        struct hash_tfm hash;
        struct compress_tfm compress;
        struct rng_tfm rng;
    } crt_u;

    void (*exit)(struct crypto_tfm *tfm);

    struct crypto_alg *crt_alg;

    void *crt_ctx[] CRYPTO_MINALIGN_ATTR;
};

我完全不知道如何使用这个结构。所以基本上我完全迷失了这个

使用它的函数需要一个结构crypto_tfm *tfm

第一个想法如下:

struct crypto_tfm *new_tfm()
{
    struct crypto_tfm *tfm = malloc(sizeof(struct crypto_tfm));
    tfm -> crt_flags = 0;
    tfm -> crt_u.
}

但我不知道如何走得更远,

联合中的给定结构也在使用另一个结构。现在对我来说有点太复杂了

【问题讨论】:

  • 更多细节?例如你不明白的等等。
  • 你可以点赞tfm -> crt_u.ablkcipher,tfm -> crt_u.aead..等
  • 联合内的结构内的整个结构。这让我很困惑。以及如何使 struct crypto_tfm *tfm 将其传递给使用它的函数
  • 只需在结构的基本初始化后将tfm 传递给您的函数,并像struct crypto_tfm *rec_tfm 这样接收方。

标签: c struct unions


【解决方案1】:

这是未经测试的,但应该是一个很好的例子:

struct st_a
{
  int a;
};

struct st_b
{
  int b;
};

union un_c
{
  struct st_a aa;
  struct st_b bb;
};

struct st_d
{
  int d;
  union un_c cc;
};

int main ()
{
  struct st_d *dd = malloc (sizeof (struct st_d));
  dd->d = 0;
  /* The following two lines might (probably are) accessing
     the same area of memory.  */
  dd->cc.aa.a = 0;
  dd->cc.bb.b = 1;
}

【讨论】:

  • 所以我肯定还必须使用每个变量结构或结构内的任何东西,或者只是我需要的东西?
  • 在我给您的示例中,您通常只能访问cc.aa.a 或 cc.aa.b,具体取决于哪个有效。在这种情况下,有一些标志是正常的,比如d,它不是联合的一部分,它会指导你知道联合的哪个部分是有效的。联合体的所有成员通常会共享相同的内存,因此同时访问联合体的多个成员(通常)没有多大意义。
猜你喜欢
  • 2019-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多