第10课 struct 和 union 分析

1. struct的小秘密

(1)C语言中的struct可以看作变量的集合

(2)struct的问题——空结构体占用多的内存?

【实例分析】空结构体的大小

#include <stdio.h>

struct TS
{

};

int main()
{
    struct TS t1;
    struct TS t2;

    //VC、BCC下定义空结构体编译器直接报错,gcc下空结构体大小为0
    printf("sizeof(struct TS) = %dn", sizeof(struct TS));
    printf("sizeof(t1) = %d, &t1 = %pn", sizeof(t1), &t1);
    printf("sizeof(t2) = %d, &t2 = %pn", sizeof(t2), &t2);

    return 0;
}

2. 结构体与柔性数组

(1)柔性数组即数组大小待定的数组

(2)C语言中可以由结构体产生柔性数组

(3)C语言中结构体的最后一个元素可以是大小未知的数组

struct SoftArray
{
  int len;
  int array[]; //array仅是一个待使用的标识符。与指针不同,编译器
               //不为array变量分配空间,因为也不知道array究竟
               //多大。只是用来作为一个标识符,以便以后可以通过这
               //个标识符来访问其中的内容。所以sizeof(SoftArray)=4
}

(4)柔性数组的用法

第10课 struct 和 union 分析

 struct SoftArray* sa = NULL;
 //注意,因sizeof柔性数组并不包含array大小,所以要开辟的空间总大小应等于
 //柔性数组+数组各元素所占的空间,即空间大小等于结构体的大小(len域)加上数组的大小
 sa = (struct SoftArray*)malloc(sizeof(struct SoftArray)+sizoef(int)*5);
 sa->len = 5;

【实例分析】柔性数组使用分析

#include <stdio.h>
#include <malloc.h>

struct SoftArray
{
    int len;
    int array[];
};

struct SoftArray* create_soft_array(int size)
{
    struct SoftArray* ret = NULL;

    if( size > 0 )
    {
        ret = (struct SoftArray*)malloc(sizeof(struct SoftArray) + sizeof(int) * size);

        ret->len = size;
    }

    return ret;
}

void delete_soft_array(struct SoftArray* sa)
{
    free(sa);
}

void func(struct SoftArray* sa)
{
    int i = 0;

    if( NULL != sa )
    {
        for(i=0; i<sa->len; i++)
        {
            sa->array[i] = i + 1;
        }
    } 
}

int main()
{
    int i = 0;
    struct SoftArray* sa = create_soft_array(10);

    func(sa);

    for(i=0; i<sa->len; i++)
    {
        printf("%dn", sa->array[i]);
    }

    delete_soft_array(sa);

    return 0;
}

3. C语言中的union

(1)C语言中的union在语法上与struct相似

(2)union只分配最大成员的空间,所有成员共享这个空间

第10课 struct 和 union 分析

(3)union的使用受系统大小端的影响

第10课 struct 和 union 分析

【编程实验】判断系统的大小端

#include <stdio.h>

int system_mode()
{
    union SM
    {
        int i;
        char c;
    };

    union SM sm;

    sm.i = 1;

    return sm.c;
}

int main()
{
    //返回1时为小端,0为大端模式
    printf("System Mode: %dn", system_mode());
    return 0;
}

4. 小结

(1)struct中的每人数据成员有独立的存储空间

(2)struct可以通过最后的数组标识符产生柔性数组

(3)union中的所有数据成员共享同一个存储空间

(4)union的使用会受到系统大小端的影响

原文链接: https://www.cnblogs.com/5iedu/p/5319180.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    第10课 struct 和 union 分析

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/394578

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月3日 下午3:49
下一篇 2023年4月3日 下午3:50

相关推荐