7

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 :)

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Corrosif
  • 97
  • 1
  • 6

2 Answers2

12

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

some_function((struct pint) {5, 10});
haccks
  • 104,019
  • 25
  • 176
  • 264
  • 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. – mafso Jun 18 '14 at 19:03
  • 3
    @mafso As the `struct` is passed by value anyway (this question is about C, not C++), the argument about its lifetime is mute. – cmaster - reinstate monica Jun 18 '14 at 19:09
  • Note that the parentheses around the function argument are superfluous. `some_function((struct point){5, 10});` works just as well. – cmaster - reinstate monica Jun 18 '14 at 19:10
  • @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. – mafso Jun 18 '14 at 19:11
  • @cmaster; Yes. I often do mistake in parenthesizing :) – haccks Jun 18 '14 at 19:12
  • 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. – keltar Jun 18 '14 at 19:14
  • @mafso 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++). – cmaster - reinstate monica Jun 18 '14 at 19:18
  • 5
    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). – AnT stands with Russia Jun 18 '14 at 19:29
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.