The folowing piec of code generates error: initializer element is not constant
at compile time on the line declaring and initializing the user struct variable.
#include <stdio.h>
#include <stdlib.h>
struct user_s {
char *name;
void (*(*pred_skip_func))(int);
};
void f1 (int skip) {
printf("I am f1\n");
}
void f2 (int skip) {
printf("I am f2\n");
}
void (*(*pred_skip_func))(int);
struct user_s user = {"Manu", pred_skip_func};
int main(void) {
struct user_s tmp;
pred_skip_func = malloc(sizeof(tmp.pred_skip_func) * 2);
pred_skip_func[0] = f1;
pred_skip_func[1] = f2;
int i;
for (i = 0; i < 2; i++) {
(*(user.pred_skip_func)[i]) (i);
}
return EXIT_SUCCESS;
}
Moving the initialization in the main function solves the issue, but I want to understand why ? Is there any restriction on structure initialisation ?
More over, as you can see, I created a tmp user_struc variable to get the size of my pointer to function pointers because I was not able to do this in a cleaner way. How can I fix this ?
First question:
“Is there any restriction on structure initialisation ?”
C requires initializers for aggregate types with static storage duration to be constant:
Note that in C89 even if the object of the aggregate type had automatic storage duration the intializers had to be constant expressions (this is no longer the case in C99).
Second question:
“More over, as you can see, I created a tmp user_struc variable to get the size of my pointer to function pointers because I was not able to do this in a cleaner way.”
You can use your
userobject to compute the size of the member:or use a C99 compound literal if you have not declared any object of the structure type: