开发者

Structure Declaration in C

开发者 https://www.devze.com 2023-03-26 06:24 出处:网络
Whether following structure declaration is right. typedef struct{ int roll; intage ; } class[10]; When I do like this , compiler does not say any error.

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,

am getting error. So here class[0] struct variabl开发者_如何学Pythone or structure name..

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消