Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize an array of structs with function pointers in them C

I am trying to initialize an array of structs. the structs have function pointers in them and are defined as such:

typedef struct{
      char str[512];
      char *fptr;
} infosection;

then I try to make an array:

infosection section[] = {
      ("Software", *SoftwarePtr),
      ("Hardware", *HardwarePtr),
 }

I defined the function pointers using a simple tutorial. Function Software returns an int

int (*SoftwarePtr)()=NULL;
SoftwarePtr = &Software;

My question is about the warnings I get upon compiling.

Initialization makes integer from pointer without a cast

The warning references the lines in the section array.

So I have two doubts:

  1. Am I misusing the */&/neither for the pointer?I have tried combinations of each and i still seem to get the same warning.I am aware of the meaning of each, just unsure how they apply in this particular instance.
  2. Can I declare an instance of the infosection struct in an array as i do here?I have seen many examples where people declare their array of struct in a for loop, However my final product requires a long list of structs to be contained in that array.I would like to make my code portable such that people can add structs ( strings which correspond with functions to point to) in an easy list-like fashion as seen about. Is this the only way to declare an instance of the array

      infosection section[];
      section[0].str="software";
      section[0].fptr=SoftwarePtr;
    

Just to clarify, i have done quite a bit of research on structs, array of structs, and function pointers. It just seems that the combination of the 3 is causing trouble.

like image 419
Umphishrey's McGee Avatar asked Jul 26 '13 17:07

Umphishrey's McGee


1 Answers

One

One mistake I an find, in structure declaration of function pointer is incorrect:

typedef struct{
      char str[512];
      int (*fptr)();  // not char* fptr
} infosection;

Two

declaration:

infosection section[] = {
      ("Software", *SoftwarePtr),
      ("Hardware", *HardwarePtr),
 }

Should be:

infosection section[] = {
      {"Software", SoftwarePtr},
      {"Hardware", HardwarePtr}
 }

Remove *. and replace inner ( ) with { }.

three:

infosection section[];
section[0].str="software"; // compiler error
section[0].fptr=SoftwarePtr;

Is wrong you can't assign string in this way. you need to use strcpy() as follows;

strcpy(section[0].str, "software");
like image 179
Grijesh Chauhan Avatar answered Oct 06 '22 01:10

Grijesh Chauhan