C语言结构体篇 结构体
生活随笔
收集整理的這篇文章主要介紹了
C语言结构体篇 结构体
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在描述一個(gè)物體的屬性的時(shí)候,單一的變量類型是無法完全描述完全的。所以有了靈活的結(jié)構(gòu)體變量。 結(jié)構(gòu)體變量從意義上來講是不同數(shù)據(jù)類型的組合,從內(nèi)存上來講是在一個(gè)空間內(nèi)進(jìn)行不同的大小劃分。
1.1 結(jié)構(gòu)體類型變量的定義
struct 結(jié)構(gòu)體名{結(jié)構(gòu)體成員;};?struct student{unsigned int id;char name[10];float score[5];//...}; ?
1.2 結(jié)構(gòu)體變量的聲明
定義了結(jié)構(gòu)體變量后,并沒有在內(nèi)存中開辟相應(yīng)的空間,只有聲明了變量之后,才是開辟了相應(yīng)的結(jié)構(gòu)體空間。
struct student stu1;struct student stu2; ?
1.3 結(jié)構(gòu)體成員變量的使用
stu1.id = 10000;stu1.name = "kmist"stu1.score[1] = 100;//... ?
1.4 ‘.’ 和 ‘->’ 的區(qū)別 如果發(fā)生了地址跳轉(zhuǎn),就使用->
//定義一個(gè)student結(jié)構(gòu)體struct student{long id;char name[10];//...
};?//定義一個(gè)class結(jié)構(gòu)體,其中聲明了student的結(jié)構(gòu)體.struct class{int room;struct student stu1;struct student stu2;};?//聲明class 結(jié)構(gòu)體變量struct class class1;class1.room = 1; //直接成員變量用 .class1->stu1.id = 1001; //訪問其他空間地址用 -> ,包括數(shù)組等.class2->stu2.id = 1002;? ?
1.5 結(jié)構(gòu)體動(dòng)態(tài)空間的劃分
有的時(shí)候只是臨時(shí)需要申請(qǐng)一個(gè)動(dòng)態(tài)空間,用完以后就可以釋放,這樣能節(jié)省程序運(yùn)行時(shí)的內(nèi)存空間.
#include <stdlib.h>struct student *stu = (struct student *)malloc(sizeof(struct student));stu->id = 1001; //通過地址訪問,用->printf("%d\n",stu->id);free(stu); ?
1.6 結(jié)構(gòu)體數(shù)組
struct student{int id;char name[10];};?struct student stu[2]={1001,"kmist"};struct student *p = stu; //p = stu[0]; (p+1) = stu[1]//將stu[0] 里的內(nèi)容拷貝到 stu[1]中//stu[1]->id = stu[0]->id; xx 這是錯(cuò)誤的寫法,結(jié)構(gòu)體等空間的拷貝要用拷貝函數(shù)memcpy((p+1),p,sizeof(struct student));?//使用printf("%d\n",(p+1)->id); ?
?
轉(zhuǎn)載于:https://www.cnblogs.com/kmist/p/10116860.html
總結(jié)
以上是生活随笔為你收集整理的C语言结构体篇 结构体的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Protocol Buffers简明教程
- 下一篇: 【js操作url参数】获取指定url参数