C语言结构体使用总结
先复习一下 gcc 编译命令:gcc test.c - o test
一.
#include <stdio.h>
struct Student{
char name[3];
int age;
}Jack;
int main(){
printf("Hello world\n");
Jack.name[0] = 'a';
Jack.age = 11;
printf("jack.name = %c\n",Jack.name[0]);
return 0;
}
二.
#include <stdio.h>
struct Hehe{
char name[3];
int num;
};
int main(){
printf("Hello world\n");
struct Hehe he;
he.num = 66;
printf("he.num = %d\n",he.num);
return 0;
}
结构体 struct 类型 Hehe,这里不声明变量,然后在后面程序中声明变量 he 并使用。
三.上 typedef:在计算机编程语言中用来为复杂的声明定义简单的别名
#include <stdio.h>
typedef struct Haha{
int num;
}Ha;
int main(){
printf("Hello world\n");
Ha h;
h.num = 66;
printf("h.num = %d\n",h.num);
return 0;
}
在这里我们利用 typedef 为类型 Haha 定义了别名 Ha,也就是说 Ha 代表了一种类型,那么在接下来的程序中,我们可以直接使用 Ha 来声明变量的类型了。
四.结构体初始化 **注!选择自己编译器支持的方式**
方式1.按成员顺序
#include <stdio.h>
struct Test
{
char c;
int num;
};
int main(){
printf("Hello world\n");
struct Test t = {'a', 66};
printf("t.c = %c\n", t.c);
return 0;
}
#include <stdio.h>
struct Test
{
char c;
int num;
};
int main(){
printf("Hello world\n");
struct Test t = {
num : 66,
c : 'a',
};
printf("t.c = %c\n", t.c);
return 0;
}
#include <stdio.h>
struct Test
{
char c;
int num;
};
int main(){
printf("Hello world\n");
struct Test t = {
.num = 66,
.c = 'a',
};
printf("t.c = %c\n", t.c);
return 0;
}