C++数据结构和算法分享专题

10_struct和union分析

2018-03-04  本文已影响9人  编程半岛

关键词:struct、结构体与柔性数组、union、小端模式和大端模式

1. struct的小秘密

#include <stdio.h>

// 定义一个空结构体
struct TS
{

};

int main()
{
    struct TS t1;
    struct TS t2;
    
    printf("sizeof(struct TS) = %d\n", sizeof(struct TS));
    printf("sizeof(t1) = %d, &t1 = %p\n", sizeof(t1), &t1);
    printf("sizeof(t2) = %d, &t2 = %p\n", sizeof(t2), &t2);

    return 0;
}

在gcc编译器下能够编译通过,输出结果为:

sizeof(struct TS) = 0
sizeof(t1) = 0, &t1 = 0xbfe7a740
sizeof(t2) = 0, &t2 = 0xbfe7a740

在bcc编译器和vs编译器下,编译报错,不支持空结构体

2. 结构体与柔性数组

struct SoftArray
{
    int len;
    int array[];  // 仅仅为一个标识符,不占用存储空间
};
#include <stdio.h>

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


int main()
{
    printf("%d\n", sizeof(struct SoftArray));

    return 0;
}

输出结果:

4

3. 柔性数组的用法

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

// 通过结构体定义柔性数组
struct SoftArray
{
    int len;
    int array[];
};

// 创建柔性数组
struct SoftArray* create_soft_array(int n)
{
    struct SoftArray* ret = NULL;
    
    if( n > 0 )
    {
        ret = (struct SoftArray*)malloc( sizeof(struct SoftArray) + sizeof(int) * n );
        
        ret->len = n;
    }
    
    return ret;
}

// 释放内存空间
void delete_soft_array(struct SoftArray* sa)
{
    free(sa);
}

// 使用柔性数组
void use_soft_array(struct SoftArray* sa)
{
    if( sa != NULL )
    {
        for(int i=0; i<sa->len; i++)
        {
            sa->array[i] = i + 1;
        }
    }
}


int main()
{
    struct SoftArray* sa = create_soft_array(5);
    
    use_soft_array(sa);
    
    for(int i=0; i<sa->len; i++)
    {
        printf("%d\n", sa->array[i]);
    }
    
    delete_soft_array(sa);

    return 0;
}

输出结果:

1
2
3
4
5

4. C语言中的union

#include <stdio.h>

struct A
{
    int a;
    int b;
    int c;
};

union B
{
    int a;
    int b;
    int c;
};


int main()
{
    printf("sizeof(struct A) = %d\n", sizeof(struct A));
    
    printf("sizeof(union B) = %d\n", sizeof(union B));

    return 0;
}

输出结果:

sizeof(struct A) = 12
sizeof(union B) = 4

5. 小端模式和大端模式

6. union的注意事项

void system_mode()
{
    union SM
    {
        int i;
        char c;
    };
    
    union SM sm;
    
    sm.i = 1;
    
    if( 1 == sm.c )
    {
        printf("This system is Small Endian\n");
    }
    else
    {
        printf("This system is Big Endian\n");
    }
}

7. 小结

声明:此文章为本人在学习狄泰软件学院《C语言深度解析》所做的笔记,文章中包含狄泰软件资料内容一切版权归狄泰软件所有!

上一篇 下一篇

猜你喜欢

热点阅读