——黑馬程序員——C語言構造類型—結構體(一)

-----------android培訓java培訓、java學習型技術博客、期待與您交流!-----------

結構體的基本概念和結構體變量的初始化

一、基本概念

結構體:由用戶自己建立由不同類型的數據組成的組合型的數據結構

一般形式:

struct 結構體名

        {成員列表};

例如:定義一學生的結構體

struct stu{

int  num;

char *name;

char sex;

float score;

}; // 注意 此處的分號不能省

二、結構體變量定義的方法

1、先定義結構體,然後再定義結構體變量

定義一個結構體

struct student

{

//學生的學號

int num;

//學生的姓名

char *name;

//學生年齡

int age;

//學生成績

float score;

};

注意:(1)結構體變量定義完成以後,計算機並不會給結構體分配內存空間,在定義結構體變量後再分配存儲空間

定義結構體變量:struct 結構體名  結構體變量名;

struct student stu1;

stu1是變量,他是student類型的,stu1可以存儲學生的學號、姓名、年齡、成績

也可以定義多個結構體變量

struct student  stu2,stu3,stu4...;

2、定義結構體的同時定義結構體變量

struct student

{

//學生的學號

int num;

//學生的姓名

char *name;

//學生年齡

int age;

//學生成績

float score;

}stu1,stu2,stu3...;

3、使用匿名結構體定義結構體變量

struct 

{

//學生的學號

int num;

//學生的姓名

char *name;

//學生年齡

int age;

//學生成績

float score;

}stu1,stu2,stu3...;

三、結構體變量中成員的訪問

一般形式爲:結構體變量名 . 成員名

四、結構體變量的初始化

1、先定義結構體變量再初始化

定義結構體變量

struct student

{

//學生的學號

int num;

//學生的姓名

char *name;

//學生年齡

int age;

//學生成績

float score;

}stu1;

變量成員初始化

stu1 . num = 38;

stu1 . name = "張三";

stu1 . age = 18;

stu1 . score = 58f;

2、定義結構體變量同時初始化

struct student stu2 = {38,"張三",18,58f};

四、結構體變量存儲原理

結構體成員變量對齊:結構變量成員的數據類型不一致,爲了提高數據傳輸速度,計算機每次讀取變量成員的起始地址的值是某個數k的倍數,k稱爲該數據類型的對齊模數

五、結構體變量佔用內存大小的計算

1、先找對齊模數,對齊模數是結構體變量成員中佔內存最大的那個

2、計算結構體變量中各個成員所佔的字節和

#include <stdio.h>
#include <stdlib.h>
int main()
{
	//定義一個結構體 
    struct student
    {
		//學生學號  佔4個字節
		int num;
        //學生姓名  佔1個字節
        char *name;
        //學生年齡	佔4個字節
        int age;
        //學生成績	佔4個字節
        float score;
    }stu1;
    //給結構體變量在內存中佔有的大小
    printf("%d\n",sizeof(stu1));
    
	system("pause");
	return 0;
}

#include <stdio.h>
#include <stdlib.h>
int main()
{
	//定義一個結構體 
    struct A
    {
		//佔2個字節
		short a;
        //佔1個字節
        char c;           //以上兩個存在一起,
        //佔4個字節
        int i;
        //佔4個字節
        float f;
    }a;
    //給結構體變量在內存中佔有的大小
    printf("%d\n",sizeof(a));
    
	system("pause");
	return 0;
}

調整結構體變量的成員位置後結果也不一樣

#include <stdio.h>
#include <stdlib.h>
int main()
{
	//定義一個結構體 
    struct A
    {
		//佔2個字節
		short a;
         //佔4個字節
        int i;       
        
        //佔1個字節
        char c;           

        //佔4個字節
        float f;
    }a;
    //給結構體變量在內存中佔有的大小
    printf("%d\n",sizeof(a));
    
	system("pause");
	return 0;
}

六、結構體也分爲局部結構體和全局結構體

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