#include<stdlib.h>
#include<stdio.h>
#include<string.h>
// 结构体指针
struct Book{
char *name;
char *author;
int page;
};
struct Computer {
char *name;
int price;
double weight;
};
int main() {
// 结构体的大小 和字节对齐的概念 结构体的大小该怎么计算呢?,那得先说说什么是字节对齐:
// 结构体必须满足 最大的数据类型的sizeof的值整除,
// 结构体变量的大小必须是最宽基本数据类型的整数倍. 如果不够,那么他就会在这些成员中间需要添加填充字节.
// 结构体与动态内存分配
struct Computer computer = {"H", 3000, 2.3};
// Computer 0xe164a180 ,sizeof(char) 8, sizeof(int) 4, sizeof(double) 8, sizeof 24
// 根据上面的解释分析 8+4+8=20 但是因为字节对齐的需要,结构体的大小必须是成员变量字节最大的整数倍
// 最大的是 double 和 char*, 大小都是8,所以最接近20的8的最小倍数就是24
printf("Computer %#x ,sizeof(char) %lu, sizeof(int) %lu, sizeof(double) %lu, sizeof %lu\n", (unsigned int)&computer, sizeof(computer.name),
sizeof(computer.price), sizeof(computer.weight), sizeof(computer));
// 结构体动态内存分配
struct Computer *m_p = malloc(sizeof(computer)*10);
printf("initial address %#x\n", (unsigned int)m_p);
struct Computer *p = m_p;
p->name = "HP";
p->price = 100;
p->weight = 2.4;
p++;
p->name = "Lenovo";
p->price = 200;
p->weight = 4.3;
// 遍历
printf("%#x, %#x\n", (unsigned int)p, (unsigned int)m_p);
struct Computer *loop_p = m_p;
for (; loop_p < m_p+2; loop_p++){
printf("Computer name is %s\n", loop_p->name);
}
return 0;
}
输出如下:
Computer 0xe164a180 ,sizeof(char) 8, sizeof(int) 4, sizeof(double) 8, sizeof 24
initial address 0x73d02790
0x73d027a8, 0x73d02790
Computer name is HP
Computer name is Lenovo