C 语言没有其他语言的对象(object)和类(class)的概念,struct 结构很大程度上提供了对象和类的功能。
下面是struct自定义数据类型的一个例子。
- struct tag {
- member-list
- member-list
- member-list
- ...
- } variable-list;
声明了数据类型car和该类型的变量car。
- struct car
- {
- char *name;
- float price;
- int speed;
- } mycar;
- struct car myca = {"大众", 178.9, 100};
- mycar.name = "本田";
如果将 struct 变量传入函数,函数内部得到的是一个原始值的副本。
- #include
-
- struct turtle {
- char* name;
- char* species;
- int age;
- };
-
- void happy(struct turtle t) {
- t.age = t.age + 1;
- }
-
- int main() {
- struct turtle myTurtle = {"MyTurtle", "sea turtle", 99};
- happy(myTurtle);
- printf("Age is %i\n", myTurtle.age); // 输出 99
- return 0;
- }
上面示例中,函数happy()传入的是一个 struct 变量myTurtle,函数内部有一个自增操作。但是,执行完happy()以后,函数外部的age属性值根本没变。原因就是函数内部得到的是 struct 变量的副本,改变副本影响不到函数外部的原始数据。
指针变量也可以指向struct结构。
- struct book {
- char title[500];
- char author[100];
- float value;
- }* b1;
上面示例中,变量b1是一个指针,指向的数据是struct book类型的实例。
为了使用指向该结构的指针访问结构的成员,必须使用 -> 运算符,如下所示:
- b1->title;//9-2.c
- struct Books
- {
- char title[50];
- char author[50]