13、黑馬程序員-C語言結構體

------<a href="http://www.itheima.com" target="blank">Java培訓、Android培訓、iOS培訓、.Net培訓</a>、期待與您交流! -------

一、什麼是結構體


對於數組中,每個元素都是相同的,如果我們想使每個元素不同的話,我們可以考慮使用結構體。
結構體可以由多種不同類型的數據類型組成的新的數據類型

二、結構體的定義
格式:
struct 結構體名 {
    數據類型 變量1;
    數據類型 變量2;
    數據類型 變量3;
    ... ...
}

例如:
struct Student {
    int age;
    charchar *name;
};
三、結構體變量的定義

1、先定義結構體,再定義變量
struct Student {
    int age;
    charchar *name;
};
struct Student stu;

2、定義結構體的同時定義變量
struct Student {
    int age;
    charchar *name;
} stu;
 
3、直接定義結構體變量
struct {
    int age;
    charchar *name;
} stu;

四、結構體的初始化


1、聲明變量的同時初始化
struct Student {
    int age;
    charchar *name;
};
struct Student stu = {22, "hello"};

2、先聲明變量,再逐一初始化
struct Student stu;
stu.age = 22;
stu.name = "hello";
3、定義結構體的同時進行變量定義和初始化
struct Student {
    int age;
    charchar *name;
} stu = {22, "hello"};

4、非順序初始化
struct Student stu = {.name = "hello", .age = 22};

5、注意:如果沒有初始化結構體,所有變量會自動的有默認值

五、訪問結構體

1、結構體變量是基本數據類型
int age = stu.age;
charchar *name = stu.name;

2、結構體變量是結構體
struct Date {
    int year;
    int month;
    int day;
};

struct Student {
    int age;
    charchar *name;
    struct Date birthday;
};

struct Student stu = {22, "hello", {1999, 10, 10}};
int year = stu.birthday.year;
int month = stu.birthday.month;
int day = stu.birthday.day;
3、相同結構體類型變量間可以整體賦值

struct Student stu1 = {23, "hello"};
struct Student stu2 = stu1;     // 把結構體變量stu1的值對應的賦值給stu2,所以stu2 = {23, "hello"}

六、結構體數組

1、三種定義方式:
// 方式一
struct Student {
    int age;
    charchar *name;
} stus[3];

// 方式二
struct Student {
    int age;
    charchar *name;
};
struct Student stu[3];

// 方式三
struct {
    int age;
    charchar *name;
} stus[3];

2、初始化
和數組的初始化一樣,可以參照數組筆記。
stus = {{12, "hello"}, {23, "world"}, {24, "welcome"}}

七、結構體指針

1、格式
struct 結構體名 *指針名;

2、訪問結構體的方式增加了
之前訪問結構體的方式是
結構體變量名.成員變量名
現在增加了
(*指針名).成員變量名
指針名->成員變量名

3、例子
struct Student {
    int age;
    charchar *name;
};

struct Student stu = {23, "hello"};
struct Student *p = &stu;

printf("%d, %s\n", stu.age, stu.name);
printf("%d, %s\n", (*p).age, (*p).name);
printf("%d, %s\n", p->age, p->name);
八、結構體與函數

1、結構體作爲函數參數
結構體實參會把成員變量值對應的賦值給函數結構體參數對應的變量值,改變函數結構體參數不會影響到實參。
struct Student {
    int age;
    charchar *name;
};
void test(struct Student s)
{
    // 對結構體s的操作不會影響到stu
    s.age = 10;
    s.name = "world";
}
int main()
{
    struct Student stu = {23, "hello"};
    test(stu);
    printf("%d, %s\n", stu.age, stu.name);
    return 0;
}
輸出:
23, hello

2、結構體指針作爲函數參數
struct Student {
    int age;
    charchar *name;
};

void test(struct Student * s)
{
    // 對結構體s的操作會影響到stu
    s->age = 10;
    s->name = "world";
}

int main()
{
    struct Student stu = {23, "hello"};
    test(&stu);
    printf("%d, %s\n", stu.age, stu.name);
    
    return 0;
}

輸出:

10, world


------<a href="http://www.itheima.com" target="blank">Java培訓、Android培訓、iOS培訓、.Net培訓</a>、期待與您交流! -------

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