Reputation: 11169
I'm getting a compile time error during initialization of the members structure in this code. What can be some other methods to initialize the below array structure. Thank you!
#include <stdio.h>
#include <stdlib.h>
#define MAX_FUNC_MEMBERS 100
#define MAX_FUNC_DESC_STR 50
typedef struct member_struct {
double degree;
double coefficient;
} member;
typedef struct function_struct{
member members[MAX_FUNC_MEMBERS];
char *description;
} *function;
function malloc_function() {
return (function) malloc(sizeof(struct function_struct));
}
double compute_function(function f, double x) {
return 0.0;
}
int main(void) {
// f1 = x^2
function f;
f->members = {
[0] = {2.0, 1.0},
[1] = {1.0, 1.0}
};
f->description = "x squared";
return 0;
}
Upvotes: 2
Views: 1849
Reputation: 25855
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:
function
structs in a very tight loop for that to be a problem, however. :)Upvotes: 2
Reputation: 96937
You have a char *
but you haven't allocated memory for the string it will point to.
You could do something like:
function f = malloc(sizeof(function));
const char *desc = "x squared";
f->description = malloc(strlen(desc) + 1);
strcpy(f->description, desc);
To verify that it works:
fprintf(stderr, "description: %s\n", f->description);
Upvotes: 0