C语言 结构体

mac2024-03-26  28

结构体

================================================================ 结构体是C语言的一种数据类型,和基本数据类型一样。结构体可以将不同类型的数据封装成一个集合方便我们进行调用。它本身不占据系统空间,只有在定义变量的时候才分配系统空间。

结构体的内容在内存中是如何分配的?
首先判断结构体中的数据类型最大占多少字节:例如最大为1个字节时(char):则按一字节对齐;最大为2字节时(short):则按2字节对齐;最大为4字节或以上的(int):则按4字节对齐 (32位机)。另外long在32位机中不是8字节而是4字节。最大位8字节或以上的(long):则按8字节对齐(64位机)。16位IBM-PC按一字节对齐,int为2字节。
如何对齐呢?
因为结构体在内存分配空间是连续的,假如为4字节对齐时,char类型也分配4个字节,剩余的3个字节则看下一个类型是否刚好放下,如果放不下则另外分配空间。指针类型不用看它所指向的内容是什么类型,一律看作4字节(32位)或8字节(64位)。

================================================================

应用

1.设计一个时间结构体,从系统获取时间并且初始化
#include <stdio.h> #include <time.h> //设计一个时间结构体,从系统获取时间并初始化。 int main(int argc, char const *argv[]) { struct _time{ int year; int mon; int day; int hour; int min; int sec; }; struct _time my_time; //获取时间间距 time_t timep = time(&timep); //将时间间距转换为时间结构体 struct tm sys_time = *(gmtime(&timep)); //初始化自定义结构体 my_time.year = sys_time.tm_year + 1900 ; my_time.mon = sys_time.tm_mon + 1 ; my_time.day = sys_time.tm_mday; my_time.hour = sys_time.tm_hour + 8 ; my_time.min = sys_time.tm_min; my_time.sec = sys_time.tm_sec; //显示时间 printf("系统时间为: %d-%02d-%02d\t%02d:%02d:%02d\n", my_time.year, my_time.mon, my_time.day, my_time.hour, my_time.min, my_time.sec); //printf("%s\n", ctime(&timep)); return 0 ; }
2.结构体空间大小计算:
struct Data{ int *a; char *b[10]; float c; void (*fun[5])(int); int (*d)[10]; char e[4]; };

32位编译系统: 4+40+4+20+4+4 = 76 64位编译系统: 8+80+8+40+8+8 = 152 关于类型占几个字节 16位 32位 64位都不一样 https://blog.csdn.net/sifanlook/article/details/71419858

最新回复(0)