struct和typedef struct在c語言中的用法

struct和typedef struct在c語言中的用法

在c語言中,定義一個結構體要用typedef ,例如下面的示例代碼,Stack sq;中的Stack就是struct Stack的別名。

如果沒有用到typedef,例如定義

struct test1{
int a;
int b;
int c;

};

test1 t;//聲明變量

下面語句就會報錯

struct.c:31:1: error: must use 'struct' tag to refer to type 'test1'

test1 t;

^

struct 

1 error generated.

聲明變量時候就要用struct test1;這樣就解決了

 

如果這樣定義的話

typedef struct test3{
int a;
int b;
int c;
}test4;

test3 d;
test4 f;

此時會報錯

struct.c:50:1: error: must use 'struct' tag to refer to type 'test3'

test3 d;

^

struct 

1 error generated.

所以要struct test3這樣來聲明變量d;

 

分析一下:

上面的test3是標識符,test4 是變量類型(相當於(int,char等))。

 

 我們可以用struct test3 d來定義變量d;爲什麼不能用test3 d來定義是錯誤的,因爲test3相當於標識符,不是一個結構體,struc test3 合在一起才代表是一個結構類型。

所以聲明時候要test3時候要用struct test3 d;

 

typedef其實是爲這個結構體起了一個新的名字,test4;

typedef struct test3 test4;

test4 相當於struct test3;

就是這麼回事。

 

複製代碼

#include<stdio.h>
#include<stdlib.h>

typedef struct Stack
{
char * elem;
int top;
int size;
}Stack;

struct test1{
int a;
int b;
int c;

};

typedef struct{
int a;
int b;
int c;

}test2;
int main(){

printf("hello,vincent,\n");
Stack sq;
sq.top = -1;
sq.size=10;
printf("top:%d,size:%d\n",sq.top,sq.size);

// 如果定義中沒有typedef,就要用struct test1聲明變量,否則報錯:
struct test1 t;
t.a=1;
t.b=2;
t.c=3;
printf("a:%d,b:%d,c:%d\n",t.a,t.b,t.c);

test2 e;
e.a=4;
e.b=5;
e.c=6;
printf("a:%d,b:%d,c:%d\n",e.a,e.b,e.c);
return 0;

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章