Whether following structure declaration is right.
typedef struct {
int roll;
int age ;
} class[10];
When I do like this , compiler does not say any error.
But, when I assign class[0].age=10,
Thanks
You are defining a type class
which is an array of ten structs. To use this type you have to instatiate a variable of that type:
class x;
x[0].age = 10;
Maybe a slightly cleaner way would be to have two separate typedefs:
typedef struct { int roll; int age; } foo_unit;
typedef foo_unit foo_array[10];
foo_array x; /* now an array of 10 foo_units. */
foo_unit y[10]; /* same thing */
I think what you want to do is
struct {
int roll;
int age ;
} class[10];
In your current code, class is defined as a type, because of the typedef. It's fine to define types this way, but you have to declare a variable afterwards:
typedef struct {
int roll;
int age ;
} class_type[10];
class_type class;
By making this typedef, you define a type. So in order to get your desired effect you should do the following:
class myclass;
myclass[0].age = 1;
class
is the type name of an array of 10 elements each equal to the struct you define.
You should instantiate the type:
class classObject;
You have been possibly mislead by the basic syntax for declaring a struct:
struct class {
int roll;
int age ;
} class[10];
this declaration will also define a variable, array of 10 struct class
.
By prefixing it with typedef
you are changing the way the declaration works, and defining instead the type name instead of an instance of the struct.
精彩评论