简体   繁体   English

C语言中的结构声明

[英]Structure Declaration in C

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, 但是,当我分配class[0].age=10,
am getting error. 出现错误。 So here class[0] struct variable or structure name.. 因此,这里的class [0]结构变量或结构名称。

Thanks 谢谢

You are defining a type class which is an array of ten structs. 您正在定义一个类型 class ,它是由十个结构组成的数组。 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:

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. 在当前代码中,由于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. 通过创建此typedef,可以定义类型。 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. class是由10个元素组成的数组的类型名称,每个元素等于您定义的结构。

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 . 此声明还将定义一个变量,由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. 通过给它加上typedef作为前缀,您可以更改声明的工作方式,并定义类型名称而不是结构实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM