- void指针
- 结构体
- 联合体
- 枚举
- 函数及其指针
- typeof
一、结构体
C语言中的结构体与java中的对象很像。结构体中每一个变量分配不同的内在空间,所以结构体所占内存的大小是变量类型叠加和。它有三种定义方式
- 1.标准定义
struct Student{// struct 结构体名 : 结构体类型
char name[20];
int id;
int age;
float score;
}
- 2.定义加声明变量
struct Student{// struct 结构体名 : 结构体类型
char name[20];
int id;
int age;
float score;
}s2;
- 3.类似匿名的
struct
{
int age;
float score;
char sex;
} st3;
对于第一种和第二种,可以在其它地方创建结构体变量:
struct Student st = {80,55.5,'F'};
struct Student st2;
struct Student *p = &s1;//定义指向struct Student结构体变量的指针变量
声明后的引用结构体变量的成员格式如下:
//结构体变量访问成员变量
s1.age = 10;
strcpy(s1.name,"zhangsan");//类似于java中的s1.name = "zhangsan",c中字符串只能这样赋值
(*p).id = 101;//结构体指针变量访问其指向的结构体变量的成员变量
p->id = 102;
二、联合体
联合体总内存,以成员中某个变量最大值为准。
union Un{
int a;
long b;
double c;
};
三、枚举
枚举中每个数值默认按顺序递增,某一变量赋值后,后面的值依次以1递增(前面值不变)
enum WeekDay
{
Monday=8,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
};
四、void指针
int main(){
char *p = NULL;
int *q = NULL;
void *t = NULL;
p = (char *)q;
t = q;// void *类型指针变量可以接收任意类型指针赋值
p = t;// void *类型指针可以向任意类型指针变量赋值
return 0;
}
五、函数及其指针
函数名代表函数的入口地址。函数的入口地址:函数存在text代码段的起始编号。
1.定义函数指针变量方法
void fun1(int a);//函数的声明
void *fun2(int arr[],int n); 《=》 void *fun2(int *arr,int n);
void (*ptr_fun)(int);//函数指针变量的定义
ptr_fun = fun1;
void * (*ptr_f)(int *,int) = fun2;//函数指针变量的定义
2.利用函数指针调用函数
fun1(a);//通过函数名调用
//通过函数指针变量调用
ptr_fun(a);
// (*ptr_fun)(a);
3.利用函数指针实现函数回调
int add(int a,int b);
//带函数指针变量形参的函数
int calc(int a,int b,int (*pfun)(int,int)){
return pfun(a,b);
}
result = sub(a,b); //直接调用
result = calc(a,b,add);//函数的回调
int add(int a,int b);
int sub(int a,int b);
int calc(int a,int b,int (*pfun)(int,int)){
return pfun(a,b);
}
int main(){
int a = 10;
int b = 40;
int result = 0;
result = add(a,b);
printf("result = %d\n",result);
result = sub(a,b); //直接调用
printf("result = %d\n",result);
result = calc(a,b,add);//函数的回调
printf("result = %d\n",result);
result = calc(a,b,sub);//函数的回调
printf("result = %d\n",result);
return 0;
}
int add(int a,int b){
return a + b;
}
int sub(int a,int b){
return a - b;
}
六、typedef关键字
typedef用于给存在的数据类型起别名。
int a;//a是一个标识符 a是一个变量名
typedef int a;//a还是一个标识符,a是int类型的别名,别名和原类型完全等价
struct Student{
}stu;//stu是一个标识符,stu是结构体变量名
typedef struct Student stu;//stu是一个标识符,stu是struct Student类型别名
void (*ptr_fun)(int);//ptr_fun是一个标识符,函数指针变量名
typedef void (*ptr_fun)(int); //ptr_fun是函数指针类型别名
ptr_fun p;