I have declared this array of unions:
union Function {
char* name;
double (*fnct)();
int args;
};
union Function functions[] = {
{.name = "acos", .fnct = acos, .args = 1},
{.name = "asin", .fnct = asin, .args = 1},
{.name = "atan", .fnct = atan, .args = 1},
};
But, when I try to use it I get an Segmentation fault error.
for(int i = 0; i < sizeof(functions) / sizeof(union Function); i++) {
printf("%d\n", functions[i].args);
printf("%s\n", functions[i].name); //HERE!
}
A union contains either of its members, not all of its members.
So the last initializer is the final one, meaning its value is just 1. So printing the name ( a string) results in a seg fault because printf tries to dereference the address 1.
If you want to have all of its members, use struct instead of union.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With