C function and struct on the fly
Asked Answered
U

2

8

I would to know if t's possible in to initialise struct on the fly for function call like in c++ :

struct point {
  int x;
  int y;
};

some_function(new point(x,y));

Thx :)

Urogenital answered 18/6, 2014 at 18:47 Comment(0)
A
13

Yes. You can use compound literals, introduced in C99.

some_function((struct pint) {5, 10});
Arleta answered 18/6, 2014 at 18:48 Comment(8)
I didn't downvote, but I think, you should point out, that the structure's storage duration ends with the end of the enclosing block. And afaik there is no way of doing something similar with dynamic memory.Prelacy
@Prelacy As the struct is passed by value anyway (this question is about C, not C++), the argument about its lifetime is mute.Cosmism
Note that the parentheses around the function argument are superfluous. some_function((struct point){5, 10}); works just as well.Cosmism
@cmaster: Yes, you're totally right. But in the question, a pointer is passed. So this is not really equivalent. But yes, the lifetime is not the problem.Prelacy
@cmaster; Yes. I often do mistake in parenthesizing :)Arleta
For new-like approach, just make a function that will malloc and fill fields. Also, in C99 structures could be assigned to each other, so *ptr_to_struct = (type){1, 2, 3} is quite valid.Insobriety
@Prelacy Ah, yes, I see what you mean. Then again, new is not even a keyword in C, and its usage indicates to me that the OP seems to have a strong Java background (there is no such thing as an object on the stack in Java). So I guessed that what he really meant was to pass a throwaway object, which should be passed on the stack in C (as const reference in C++).Cosmism
It is worth noting that compound literals are lvalues, which means that one can also do some_function(&(struct pint) {5, 10}). This is a bit closer to the original request in a sense that it produces a pointer argument (but it does not produce dynamic lifetime, of course).Sixtyfour
O
0

You can do it in C and call your function like this guy said, but you'll need to add the flag -std=c99 to your gcc invocation line, else it might failed if you're using some -W* flags.

Opah answered 18/6, 2014 at 18:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.