C语言学习笔记--struct 和 union关键字

1.struct关键字

C 语言中的 struct 可以看作变量的集合struct中的每个数据成员都有独立的存储空间。

结构体与柔性数组

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

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

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

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

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

(4)柔性数组的用法

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

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

2.union关键字

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

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

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

int main()
{
    printf("sizeof(A) = %d\n",sizeof(A));//12
    printf("sizeof(B) = %d\n",sizeof(B));//4
}

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

判断系统的大小端

#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: %d\n", system_mode());
    return 0;
}

 

 

参考资料:
www.dt4sw.com
http://www.cnblogs.com/5iedu/category/804081.html

posted @ 2016-09-22 09:26  CrazyDiode  阅读(2409)  评论(0编辑  收藏  举报