zoukankan      html  css  js  c++  java
  • struct和union

    struct的小秘密

    C语言中的struct可以看做变量的集合,struct的问题:

    空结构体占用多大内存?

    例子1:空结构体的大小

    #include<stdio.h>
    struct ST
    {
    
    };
    int main()
    {
        printf("sizeof(struct ST) = %d
    ",sizeof(struct ST));
        return 0;
    }
    
    

    这是C语言的灰色地带,各种解释没有谁对谁错。

    结构体与柔性数组

    • 柔性数组是大小待定的数组
    • C语言中可以由结构体产生柔性数组
    • C语言中结构体的最后一个元素可以是大小未知的数组

    例子2:柔性数组分析

    #include<stdio.h>
    #include<stdlib.h>
    typedef struct _SoftArray
    {
       int len;
       int array[];
    }SoftArray;
    
    int main()
    {
        int len = 10,i=0;
        SoftArray *p = (SoftArray*)malloc(sizeof(SoftArray)+sizeof(int)*len);
        p->len = len;
        for(i-0;i<len;i++)
        {
            p->array[i] = i+1;
        }
        for(i=0;i<len;i++)
            printf("array[%d] = %d
    ",i,p->array[i]);
    
        free(p);
        return 0;
    }
    
    

    C语言中的union

    C语言中的union在语法上与struct相似,union只是分配最大成员的空间,所有成员共享这个空间。

    例子3:struct和union

    struct A
    {
    	int a;
    	int b;
    	int c;
    };
    union B
    {
    	int a;
    	int b;
    	int c;
    };
    int main()
    {
    	printf("%d
    ",sizeof(struct A));
    	printf("%d
    ",sizoef(struct B));
    	return 0;
    }
    

    union的注意事项

    union的使用受到系统小大端的影响

    例子4:判断大小端的模式

    union A
    {
        int a;
        char c;
    };
    int main()
    {
        union A test;
        test.a = 0x1234;
        printf("test.c = %x
    ",test.c); //34
        return 0;
    }
    

    由上面结果可以知道,本机为小端模式。

    小结

    • struct中每个成员有独立的存储空间
    • struct可以通过最后的数组标识符产生柔性数组
    • union中所有数据成员共享同一个内存空间
    • union的使用会受到系统大小端的影响
  • 相关阅读:
    Python爬虫技术--基础篇--函数式编程(上篇)
    Python爬虫技术--基础篇--Python高级特性
    Python爬虫技术--基础篇--函数(下篇)
    Python爬虫技术--基础篇--函数(上篇)
    Python爬虫技术--基础篇--字典和集合
    Python爬虫技术--基础篇--列表和元组
    1013 数素数
    1012 数字分类
    1010 一元多项式求导
    1011 A+B 和 C
  • 原文地址:https://www.cnblogs.com/yanyun888/p/9145040.html
Copyright © 2011-2022 走看看