简体   繁体   中英

How to use struct within an union, within a struct in C?

i am currently having a lot of struggle with a, for me personally, very complex structure

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;
};

I completely have no idea how to use this struct. so basicly i am completely lost with this

the function using this expects a struct crypto_tfm *tfm

first idea is the following:

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

but i dont know how to get further,

the given structs within the union are also using another structs. kinda too complicated for me right now

This is untested, but should be a good example:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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