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

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