Declaring variables inside a struct in c [duplicat

2019-10-08 16:05发布

问题:

This question already has an answer here:

  • Why can't we initialize members inside a structure? 6 answers

I wanted to make an object oriented preprocessor to my programming language which converts my language into C (like early C++). And I want to simulate the classes with structures. And the question is: how can I declare a variable inside a struct like this:

typedef struct { //equivalent of class
   int a = 5;
   int (*sub)(int) = &int_sub; //function of a class, uses an external declared function
} class_name;

I tried the code above but the compiler wrote this:

error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token 
       void (*sub)(int) = &int_sub;

I have two questions:

  1. Can I declare a variable inside a struct?

  2. If yes, how?

回答1:

Alternatively, you can also initialize the variable of your struct type.

int func( int a ){}

typedef struct {
    int a;
    int (*sub)(int);
} class_name;

class_name my_struct = { .a = 5, .sub = func };


回答2:

You can't assign a pointer value inside a struct definition. You could use a function to init it.

typedef struct { //equivalent of class
   int a;
   int (*sub)(int);
} class_name;

int int_sub (int a)
{
   // your stuff
   return 0;
}

int main()
{
   class_name myClassVariable;

   myClassVariable.a = 5;
   myClassVariable.sub = int_sub;

   printf("class_name.a = %d\n", myClassVariable.a );
   printf("class_name.sub = %p\n", myClassVariable.sub );
   printf("int_sub address = %p\n", int_sub );

   return 0;
}

Or, as shown in artm answer, you could init your allocated variable:

class_name my_struct = { .a = 5, .sub = int_sub };


回答3:

I take it your question is not about how to declare but how to initialize a structure member.

Define the class as opaque type in the h file. Use typedef for function pointers.

h file

// opaque type declaration
typedef struct class_name class_name;

// types used by this class
typedef int sub_func_t (int);

// member functions of the class
class_name* class_init (int a, sub_func_t* sub);

Then initialize it from inside its constructor:

c file

struct class_name { //equivalent of class
   int a;
   sub_func_t* sub;
};

class_name* class_init (int a, sub_func_t* sub) 
{ 
  class_name* new_class = malloc(sizeof(*new_class)); 
  assert(new_class != NULL);
  *new_class = (class_name){a, sub};
  return new_class; 
}