C语言之结构体

1 概述

    结构体就是一个可以包含不同数据类型的一个结构,它是一种可以自己定义的数据类型。

2 定义结构体类型变量的方法

 定义结构体变量的一般格式为:

    struct 结构名

    {

        类型  变量名;

        类型  变量名;


        ...

    }结构变量;

    代码如下:

struct Student{
        char name[8];
        int age;
    }stu1;

    上面的代码声明了一个名为Student的结构体,它包含两个成员name和age,成员name的数据类型为字符数组,成员age的数据类型位整形,同时定义了一个Student结构体变量stu1.

注意:结构体声明的时候本身不占用任何内存空间,只有当定义结构体变量的时候计算机才会分配内存。

也可以通过 struct Student 结构体变量名; 方式定义结构体变量,代码如下:

struct Student stu2 = {"Lily",19};

还可以通过typedef 形式简化,代码如下:

typedef struct Student MyStudent;
MyStudent stu3 = {"Jake",20};

完整例子如下:

#include <CoreFoundation/CoreFoundation.h>

int main(int argc, const char * argv[])
{

    struct Student{
        char name[8];
        int age;
    }stu1;
    
    typedef struct Student MyStudent;
    
    strcpy(stu1.name, "Jackz");
    stu1.age = 20;
    printf("姓名:%s,年龄:%d\n",stu1.name,stu1.age);
    
    struct Student stu2 = {"Lily",19};
    printf("姓名:%s,年龄:%d\n",stu2.name,stu2.age);
    
    MyStudent stu3 = {"Jake",20};
    printf("姓名:%s,年龄:%d\n",stu3.name,stu3.age);
    return 0;
}

结果如下图:

wKiom1PyIUbBiLvHAAB76jdhnPY910.jpg

引申:链表的简单使用

#include <CoreFoundation/CoreFoundation.h>

int main(int argc, const char * argv[])
{
    typedef struct _Node{
        float score;
        int age;
        struct _Node *next;
    }Node;
    Node node1,node2,node3;
    node1.score = 60.5;
    node1.age = 18;
    node2.score = 80.4;
    node2.age = 19;
    node3.score = 100.2;
    node3.age = 20;
    
    node1.next = &node2;
    node2.next = &node3;
    node3.next = 0;
    
    Node curNode = node1;
    printf("分数:%.1f,年龄:%d\n",curNode.score,curNode.age);
    do {
        curNode = *curNode.next;
        printf("分数:%.1f,年龄:%d\n",curNode.score,curNode.age);
    }while (curNode.next);
    
    return 0;
}

结果如下:

wKioL1PyJnejygTqAAB9Zjxws4w418.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章