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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM