C語言之結構體

1 概述node

    結構體就是一個能夠包含不一樣數據類型的一個結構,它是一種能夠本身定義的數據類型。
數組

2 定義結構體類型變量的方法ide

 定義結構體變量的通常格式爲:
spa

    struct 結構名
blog

    {內存

        類型  變量名;
get

        類型  變量名;it


        ...
io

    }結構變量;class

    代碼以下:

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

相關文章
相關標籤/搜索