c語言struct結構體強制型別轉換

2021-10-04 05:33:34 字數 3341 閱讀 1227

1、無結構體標籤

struct gpio_t;
宣告了乙個無名結構體,並建立了乙個結構體變數gpio_t(已分配空間),該方法只適合建立乙個結構體變數

typedef struct gpio_t;

/*靜態分配記憶體*/

gpio_t gpioa;

/*動態分配記憶體*/

gpio_t *gpioa = (gpio_t*)malloc(sizeof(gpio_t));

free(gpioa);

2、顯示宣告結構體標籤

struct _gpio_t;
如需宣告多個結構體變數:struct _gpio_t gpioa,gpiob;

注:常用第二種方法宣告建立結構體,具體高階用法請看下面講解

1、普通資料型別強制轉換,使用強制型別轉換符

(type_name) expression

例如:

int sum = 17, count = 5;

double mean;

mean = (double)sum / count;

printf("value of mean : %f \n",mean);

注:這裡要注意的是強制型別轉換運算子的優先順序大於除法,因此 sum 的值首先被轉換為 double 型,然後除以 count,得到乙個型別為 double 的值

2、資料型別強制轉化為結構體型別

#include int main (void) ;

typedef struct _gpio_tgpio_t;

gpio_t *gpioa = (gpio_t *) &a;

/* * 等同於gpio_t *gpioa = (gpio_t *) &a;

* 因為陣列的首位址為 可以表示為 a,&a,&a[0]

*/ printf("%d \n",gpioa->in);

printf("%d \n",gpioa->out);

printf("%c \n",gpioa->type);

printf("%c \n",gpioa->value);

}

實用舉例:

#include typedef struct

gpio_typedef;

/*peripheral base address define*/

#define periph_base ((uint32_t)0x40000000) /*!< peripheral base address in the alias region */

#define apb2periph_base (periph_base + 0x10000)

#define gpioa_base (apb2periph_base + 0x0800)

#define gpioa ((gpio_typedef *) gpioa_base)

/*函式呼叫*/

#include "led.c"

void led_init(void)

gpio_t gpiob = ;

printf("%d \n",gpiob.in);

printf("%d \n",gpiob.out);

printf("%c \n",gpiob.type);

printf("%c \n",gpiob.value);

注:callback函式使用時,直接給成員變數賦值

*舉例說明結構體成員資料型別對齊問題1、成員變數位元組已經對齊使用

int a = ;

typedef struct _gpio_tgpio_t;

gpio_t *gpioa = (gpio_t *) &a;

printf("%c \n",gpioa->in);

printf("%c \n",gpioa->out);

printf("%c \n",gpioa->type);

printf("%c \n",gpioa->value);

printf("%d \n",gpioa->data);

編譯執行輸出結果:

注:資料儲存格式分為大小端儲存,所以結構引用輸出順序可能不太對應

2、成員變數沒有對齊

int a = ;

typedef struct _gpio_tgpio_t;

gpio_t *gpioa = (gpio_t *) &a;

printf("%d \n",gpioa->in);

printf("%d \n",gpioa->out);

printf("%c \n",gpioa->type);

printf("%c \n",gpioa->value);

printf("%d \n",gpioa->data);

編譯執行結果:

注:因為自動對齊緣故,其中有些資料會自動丟掉

3、成員變數不使用自動給對齊

int a = ;

/** arm系統使用 __packed取消位元組對齊

*/ #pragma pack(1) //強制設定1位元組對齊

typedef struct _gpio_t gpio_t;

gpio_t *gpioa = (gpio_t *) &a;

printf("%d \n",gpioa->in);

printf("%d \n",gpioa->out);

printf("%c \n",gpioa->type);

printf("%c \n",gpioa->value);

printf("%d \n",gpioa->data);

注:最後乙個成員由於對齊錯誤出現亂碼

C語言結構體struct

定義 定義結構體,要定義兩次,1定義型別,2定義變數 1定義時 不分配記憶體,和 define一樣 定義結構體的樣式,叫什麼名字,成員,句式 2再定義 分配記憶體 用著個樣式定義變數 與typedef有點像 3如果定義的是 p指標,只表示出此結構體 變數的起始位址 struct a struct a...

C語言結構體(Struct)

在c 語言中,可以使用結構體 struct 來存放一組不同型別的資料。結構體的定義形式為 struct 結構體名 結構體是一種集合,它裡面包含了多個變數或陣列,它們的型別可以相同,也可以不同,每個這樣的變數或陣列都稱為結構體的成員 member 請看下面的乙個例子 struct stu stu 為結...

C語言 結構體struct 結構體對齊

1 定義乙個結構體 順便例項結構體變數 struct tag 結構體型別名 struct tag 這兩者共同構成了結構體型別 單獨的tag 結構體型別名 不能稱之為結構體型別 結構體變數名 2 定義的同時使用typedef 相當於定義結構體 為結構體起新名字 typedef struct tag 結...