zoukankan      html  css  js  c++  java
  • 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 ", 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
    ",sizeof(A));//12
        printf("sizeof(B) = %d
    ",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
    ", system_mode());
        return 0;
    }

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

  • 相关阅读:
    【Ecstore2.0】计划任务/队列/导入导出 的执行问题
    【Ecstore2.0】第三方信任登陆问题解决_备忘
    Ecstore 2.0 报表显示空白
    【Linux】 任务调度/计划 cron
    wdcp/wdlinux一键包的php5.3版本添加Zend.so 和Soap.so
    wdcp/wdlinux 在 UBUNTU/linux 中安装失败原因之创建用户
    假如女人是一种编程语言,你会更喜欢哪一种
    Linux中的ln
    wdcp/wdlinux 常用工具及命令集
    php 数组Array 删除指定键名值
  • 原文地址:https://www.cnblogs.com/CoderTian/p/5894996.html
Copyright © 2011-2022 走看看