Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Union on C

Tags:

arrays

c

unions

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!
}
like image 963
Pablo Avatar asked Jan 26 '18 12:01

Pablo


1 Answers

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.

like image 124
Paul Ogilvie Avatar answered Sep 28 '22 03:09

Paul Ogilvie