结构体(1)
来源:互联网 发布:网店美工下载 编辑:程序博客网 时间:2024/05/21 01:58
定义结构体struct和初始化
struct student { int id; char name[100]; int age;};int main(){ struct student s1 = {1, "张三", 15}; struct student s2 = {.id = 2, .name = "李四", .age = 16}; return 0}
访问结构体成员
.操作符
struct student { int id; char name[100]; int age;};int main(){ struct student s1 = {1, "张三", 15}; struct student s2 = {.id = 2, .name = "李四", .age = 16}; printf("s1.name = %s\n", s1.name); return 0}
结构体的内存对齐模式
结构在内存的大小是和结构成员最长的那个元素相关的
编译器在编译一个结构的时候采用内存对齐模式
struct student { int id; char name[100]; int age;};int main(){ struct student s1 = {1, "张三", 15}; struct student s2 = {.id = 2, .name = "李四", .age = 16}; printf("s1 = %d\n", sizeof(s1)); return 0}结果:108
指定结构体元素的位字段
定义一个结构体的时候可以指定具体元素的位长
struct test{ char a : 2;//指定元素为2位长,不是2个字节长};
结构数组
struct student { int id; char name[100]; int age;};int main(){ struct student s[2] = {{1, "张三", 15}, {2, "李四", 16}};}
嵌套结构
struct names{ char first[100]; char last[100];};struct man{ struct names name; int age;};struct man m = { { "wang", "wu" }, 20 };
结构体的赋值
struct name a = b;结构的赋值其实就是两个结构内存的拷贝相当于: memcpy(&a, &b, sizeof(b))如果结构体成员有指针元素,那么就不能直接赋值:struct student { int id; char *name; int age;};int main(){ // 普通赋值. struct student s1 = {1, "张三", 15}; struct student s2; s2 = s1; s1.name = "hello"; print("s2.name = %s\n", s2.name); // 结果是:张三 // 创建堆内存赋值. s1.id = 1; s1.name = malloc(10); strcpy(s1.name, "hello"); s1.age = 16; s2 = s1; s1.name[1] = '0'; printf("s2.name = %s\n",s2.name); // 结果是:h0llo // 创建堆内存赋值. s1.id = 1; s1.name = malloc(10); strcpy(s1.name, "hello"); s1.age = 16; free(s1.name); s2.id = s1.id; s2.name = malloc(strlen(s1.name) + 1); strcpy(s2.name, s1.name); s2.age = s1.age; s1.name[1] = '0'; printf("s2.name = %s\n",s2.name); // 结果是:hello free(s1.name); free(s2.name); return 0;}
指向结构体的指针
–>操作符
struct student { int id; char name[100]; int age;}int main(){ struct student s1 = {1, "张三", 15}; struct student *p = &s1; printf("p.name = %s\n", p->name); return 0;}
阅读全文
0 0
- 结构体 练习1
- 结构体1
- 17-结构体1
- 结构体(1)
- 结构体学习1
- 学习笔记:Foundation(1)---NSRange结构体、NSPoint结构体
- fork1.1 tast_struct 结构体和thread_info结构体
- 1-1-日期结构体
- 从C开始_结构体_结构数组1
- 结构体struct module(1)
- 结构体对齐问题1
- 关于结构体struct(1)
- 1--3日期结构体
- 选夫婿1 结构体
- 数组、结构体、指针1
- 结构体应用(1)
- 项目1-复数结构体
- 十六周结构体1
- numpy数组基本操作
- Windows dos命令cacls和Icalcs
- TF-IDF与余弦相似性的应用
- Jsp9个内置对象
- 推荐系统学习笔记之三 LFM (Latent Factor Model) 隐因子模型 + SVD (singular value decomposition) 奇异值分解
- 结构体(1)
- 表格打印-字符串列表的列表
- 图解图的存储结构
- BZOJ 1856 [Scoi2010]字符串
- 面向对象的异常处理机制
- 一张图看懂docker命令
- Codeforces 373D Counting Rectangles is Fun【Dp】
- JavaScript之WebSocket 技术
- mycat1.6.5分片(按照天分片)