struct和typedefstruct在c语⾔中的⽤法
在c语⾔中,定义⼀个结构体要⽤typedef ,例如下⾯的⽰例代码,Stack sq;中的Stack就是struct Stack的别名。
如果没有⽤到typedef,例如定义
struct test1{
int a;
c语言struct头文件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.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);
return0;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。