一,高级声明
1,声明和定义
为了使不同的文件都可以访问同一个变量,C会区分变量的声明和定义。
1》定义
会给变量分配内存空间
在程序中,一个变量只能定义一次,不能重复定义
定义可以看作一种特殊的声明
2》声明
不会分配内存空间
在程序中,变量可以多次声明
声明一般用:extern
2,typedef关键字 ------//给已经存在的数据类型引入(取)新的别名
1》基本数据类型
格式:
typedef 原类型 别名;
例如:
typedef int I;
int main(void)
{
int a;
I b;
a = 120;
b = a;
printf("a = %d,b = %d\n",a,b);
return 0;
}
2》数组类型
格式: typedef 元素类型 别名[元素个数];
例如:
typedef int ARR[5];
int main(void)
{
int a[5] = {1,2,3,4,5};
ARR b = {1,2,3,4,5};
int i;
for(i = 0; i < 5; i++)
printf("%d ",a[i]);
printf("\n");
for(i = 0; i < 5; i++)
printf("%d ",b[i]);
printf("\n");
return 0;
}
3》指针类型
格式: typedef 指针指向的数据类型* 别名;
例如:
typedef int* IP;
int main(void)
{
int a = 120;
int* p1;
IP p2,p3;
p1 = &a;
printf("*p1 = %d\n",*p1);
p2 = &a;
p3 = &a;
printf("*p2 = %d\n",*p2);
printf("*p3 = %d\n",*p3);
return 0;
}
二,结构体
1,概念
结构体是不同类型数据的集合,把这些不同类型的数据称为结构体的成员。
c语言只给出了定义结构体类型的方法,具体的结构体类型,需要程序员自己定义,然后使用,所以,结构体是一种自定义数据类型。
2,定义结构体类型
格式:
struct 结构体标签{
成员类型 成员名;
成员类型 成员名;
.... ...
成员类型 成员名;
};
例如:
struct student{
int sno;
char name[20];
float score;
};
3,定义结构体变量
1》常规定义
struct student{
int sno;
char name[20];
float score;
};
struct student st; //定义一个结构体变量st
2》与类型同时定义
struct student{
int sno;
char name[20];
float score;
}st; //定义一个结构体变量st
3》直接定义
struct {
int sno;
char name[20];
float score;
}st; //定义一个结构体变量st
4,初始化结构体变量
1》完全初始化
struct student st = {1001,"Jack",87.45};
2》部分初始化
struct student st = {1001,"Jack"};
3》指定成员初始化
struct student st = {.name = "Jack",87.45,.sno=1002};
5,给结构体变量赋值
除了初始化之外,结构体变量不能整体赋值,只能分别给每一个成员赋值
例如:
struct student st;
st.sno = 1002;
strcpy(st.name,"Rose");
st.score = 87.45;
同类型结构体变量之间可以相互赋值
struct student s1;
s1 = st;
6,打印结构体变量 ----//只能分别打印结构体变量中的每一个成员
例如:
#include <stdio.h>
#include <string.h>
//定义结构体类型
struct student{
int sno;
char name[20];
float score;
};
int main(void)
{
//定义结构体变量
struct student st;
struct student s1;
//给结构体变量赋值
st.sno = 1002;
strcpy(st.name,"Rose");
st.score = 87.45;
s1 = st; //同类型结构体之间可以相互赋值
//打印结构体变量的值
printf("%d %s %.2f\n",st.sno,st.name,st.score);
printf("%d %s %.2f\n",s1.sno,s1.name,s1.score);
return 0;
}
7,结构体数组 -----可以保存多个结构体的信息
例如:
#include <stdio.h>
#include <string.h>
//定义结构体类型
struct student{
int sno;
char name[20];
float score;
};
int main(void)
{
int n,i;
printf("请输入元素个数:");
scanf("%d",&n);
//定义结构体变量
struct student st[n];
for(i = 0 ; i < n; i++){
printf("请输入学生信息(sno name score):");
scanf("%d%s%f",&st[i].sno,st[i].name,&st[i].score);
}
printf("-------------------\n");
for(i = 0 ; i < n; i++)
printf("%d %s %.2f\n",st[i].sno,st[i].name,st[i].score);
return 0;
}