關於 typedef & typedef struct & typedef union理解 --寫給不長腦子的我


寫作原由,今晚再次查了typedef用法,就在這用着查着中做着一個個項目,可我還是記不住;腦子里裝得是什么? 可憐
 
 
typedef    struct
問題1:
請高手幫忙解釋以下幾種結構體定義的區別:
struct{
  int x;
  int y;
}test1;

struct test
{int x;
int y;
}test1;

typedef struct test
{int x;
int y
}text1,text2;
這幾種方法把小弟弄得頭疼,不勝感激!
 
 
 
(1) struct{ int x; int y; }test1; 
好,定義了 結構 test1,
test1.x 和 test1.y 可以在語句里用了。

(2) struct test {int x; int y; }test1; 
好,定義了 結構 test1,
test1.x 和 test1.y 可以在語句里用了。
與 1 比,省寫 了 test

(3) 
typedef struct test 
{int x; int y;  // 你漏打分號,給你添上 
}text1,text2; 
只說了 這種結構 的(類型)別名 叫 text1 或叫 text2

真正在語句里用,還要寫:
text1 test1;
然后好用 test1.x test1.y

或寫 text2 test1;
然后好用 test1.x test1.y

(4)type struct {int x; int y; }test1;
這個不可以。
改 typedef ... 就可以了。
但也同 (3)一樣,還要 寫:
test1 my_st;
才能用 my_st.x 和 my_st.y
 
        
typedef union
問題2: 
#include <stdio.h> 
typedef union 
{long i; 
int k[5]; 
char c; 
}DATE; 
struct date 
{ 
int cat; 
DATE cow; 
double dog; 
}too; 
DATE max; 
main() 
{printf("%d\n",sizeof(struct date)+sizeof(max));} 

程序結果為52,搞不懂……希望能給出詳細解題過程!!!
int k[5]是占幾個字節呀??20還是10呀??
 
union是公用的,所以DATA的大小是int k[5] =4*5 = 20

struct 是自己用自己的,所以大小是4+20+8 = 32

結果就是52


免責聲明!

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



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