How can i initialize a structure with a structure pointer(using malloc) and send a value on the same expression?

StackOverflow https://stackoverflow.com/questions/23676523

  •  23-07-2023
  •  | 
  •  

Pergunta

This probably doesn't make any sense, but I wanted to get it out of my mind. How can I do this?

 struct a {   int n1; };

 struct b {   struct a *a;   int n2; };

 int main(void) 
 {

  struct b b = { (struct a*)malloc(sizeof(struct a)) {10} , 20 };
     printf("A-> %d\n B-> %d\n ", b.a->n1,  b.n2 );

 }

So what I wanted was to declare and initialize a structure of type b sending a malloc with a value already. All this on the same expression.

In a oop language I would do something like this:

 B = new B((new A()).n1=10,20);

P.S: I know I can malloc it and set a value on another instruction, I'm just curious if I can do it on the initialization.

Foi útil?

Solução 2

This probably doesn't make any sense

Indeed, it is pointless and doesn't make any sense. But if you for reasons unknown persist on doing it, then the best way is likely to use compound literals, rather than dynamic memory allocation.

  struct b b = 
  { 
    &(struct a){10}, 
    20 
  };

This way, the member struct has the same scope as the variable b, because the scope of a compound literal is the same as for a local variable. This way, no additional malloc/free is needed.

Please note that compound literals are a superfluous feature of the C language. The above C code will yield exactly the same machine code as:

  struct a a = {10};

  struct b b = 
  { 
    &a, 
    20 
  };

The difference is that the latter is more readable.

Outras dicas

You can define a function for this purpose and use it in the initializer:

struct a *a_maker(int v) { 
    struct a *p = malloc(sizeof(struct a)); 
    p->n1 = v;
    return p;
}

int main(void) {
    struct b b = { a_maker(10) , 20 };
    printf("A-> %d\n B-> %d\n ", b.a->n1, b.n2 );
    return 0;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top