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;
}


浙公网安备 33010602011771号