C语言进阶课程学习记录-struct和union分析

C语言进阶课程学习记录-struct和union分析


本文学习自狄泰软件学院 唐佐林老师的 C语言进阶课程,图片全部来源于课程PPT,仅用于个人学习记录

struct 0

实验-struct大小

#include <stdio.h>

struct TS
{

};

int main()
{
    struct TS t1;//bcc编译器会报错,不允许结构体为空
    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;
}
/*output:
sizeof(struct TS) = 0
sizeof(t1) = 0, &t1 = 0060FF00
sizeof(t2) = 0, &t2 = 0060FF00
*/

柔性数组1
柔性数组2

实验-柔性数组

#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("%d\n", sa->array[i]);
    }

    delete_soft_array(sa);

    return 0;
}
/*output:
1
2
3
4
5
6
7
8
9
10

*/

union1

实验-union

#include <stdio.h>

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

    union SM sm;

    sm.i = 1;

    return sm.c;
}


int main()
{
    printf("System Mode: %d\n", system_mode());
    return 0;
}
/*output:
System Mode: 1

*/

小结

小结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值