C语言进阶课程学习记录-struct和union分析
本文学习自狄泰软件学院 唐佐林老师的 C语言进阶课程,图片全部来源于课程PPT,仅用于个人学习记录
实验-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
*/
实验-柔性数组
#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
*/
实验-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
*/