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 :)
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 :)
Yes. You can use compound literals, introduced in C99.
some_function((struct pint) {5, 10});
struct
is passed by value anyway (this question is about C, not C++), the argument about its lifetime is mute. –
Cosmism some_function((struct point){5, 10});
works just as well. –
Cosmism 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 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 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 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.
© 2022 - 2024 — McMap. All rights reserved.