johnsondavies
johnsondavies

Reputation: 447

How do I include different types in an array of structs?

I'm writing a program that uses a lookup table to call a function or return a constant based on a match with its name. Each element in the table is defined by a tbl_entry_t struct:

typedef int (*fn_ptr_type)(int);

typedef struct {
  char *str;
  union {
    fn_ptr_type fptr;
    int number;
  };
} tbl_entry_t;

For example, here's a sample small table:

int squareFun (int x) { return x * x; }
int cubeFun (int x) { return x * x * x; }
int Hundred = 100;

char string0[] = "square";
char string1[] = "cube";
char string2[] = "hundred";

tbl_entry_t lookup_table[] = {
  { string0, squareFun },
  { string1, cubeFun },
  { string2, Hundred }
};

I want to mix fn_ptr_type and int values in the table, and I included a union in the struct to try and achieve this, but I still get a compiler warning:

{ string2, Hundred }
warning: invalid conversion from 'int' to 'fn_ptr_type {aka int (*)(int)}'

What's the correct way to do this?

Upvotes: 1

Views: 75

Answers (2)

johnsondavies
johnsondavies

Reputation: 447

@code_fodder's answer is what I was looking for, but unfortunately on my compiler, GCC, this gives the error:

  { string2, .number = Hundred }
sorry, unimplemented: non-trivial designated initializers not supported

However, I've found an ugly workaround that is accepted, and avoids the warning, which is to write:

tbl_entry_t lookup_table[] = {
  { string0, squareFun },
  { string1, cubeFun },
  { string2, (fn_ptr_type)Hundred }  // workaround
};

Upvotes: 2

code_fodder
code_fodder

Reputation: 16371

You need to specify the union item you want to initialise - otherwise it defaults to initialsing the first item:

tbl_entry_t lookup_table[] = {
  { string0, squareFun },
  { string1, cubeFun },
  { string2, .number = Hundred }  // like this
};

live eg: https://godbolt.org/z/9WobrG

Upvotes: 4

Related Questions