In your particular case, your program would also segfault even if it compiled, however, since you're assigning data to *f
without it being allocated.
There are a couple of solutions possible for you. The most straightforward would probably be to simply allocate the function
struct on the stack instead, but that would require you to either modify its typedef
not to be a pointer, or using the struct name directly. I'll go with the later for this example:
struct function_struct fbuf = {
.members = {
[0] = {2.0, 1.0},
[1] = {1.0, 1.0}
},
.description = "x squared",
};
function f = &fbuf;
Another would be to initialize the members one by one, manually:
f = malloc(sizeof(*f)):
f->members[0].degree = 2.0;
f->members[0].coefficient = 1.0;
f->members[0].degree = 1.0;
f->members[0].coefficient = 1.0;
f->description = "x squared";
A third might be to use a compound literal:
f = &(struct function_struct) {
.members = {
[0] = {2.0, 1.0},
[1] = {1.0, 1.0},
},
.description = "apa",
};
That last one does pretty much the same as the first one, only that fbuf
is anonymous.
You can also combine the second and third, if you want the memory of the struct to be allocated on the heap, rather than on the stack:
f = malloc(sizeof(*f)):
*f = (struct function_struct) {
.members = {
[0] = {2.0, 1.0},
[1] = {1.0, 1.0},
},
.description = "apa",
};
As for your "best practice" aspect, I don't think either is inherently better or worse than any other, but they do differ in some aspects:
- The third and fourth, using compound literals, require latter versions of C, so if you're aiming to be compliant with ancient C compilers, they are a bad idea. This should be a rare issue these days, however.
- The first and third allocate the data on the stack, while the second and fourth allocate the data on the heap. This is different, rather than better or worse, so pick whichever suits your scenario.
- Depending on the compiler, the second example may be faster, since it doesn't touch the 98 members that are left unused. You'd have to be initializing a lot of
function
structs in a very tight loop for that to be a problem, however. :)