结构体(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;}