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