二级指针变量
*保存指针变量的首地址
`
int a = 10;
int *p = &a;
int * *pp = &p;
printf("a = %d \n", a);
printf("*p = %d \n", *p);
printf("**pp = %d \n", **pp);
//输出结果都为10
`
动态申请和释放堆区内存
`
#include<stdio.h>
#include<stdlib.h>// 包含malloc()和 free()
int main(){
int n = 0;
printf("Input n = \n");
scanf("%d", &n);
//void *malloc()
//malloc()返回值为 void *,可以赋值给任意类型的指针变量
int *p = (int *)malloc(sizeof(int) * n);
printf("Input number: \n");
for (int i = 0; i < n; i++){
scanf("%d", (p+i));//等价于 &p[i]
}
for (int i = 0; i < n; i++){
printf("p[%d] = %d\n", i, *(p + i));
}
free(p);//释放堆区内存
p = NULL;//为了防止野指针的出现,将p指向NULL
return 0;
}
`
结构体
`
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Student{
int id;
char name[10];
float score;
};
int main(){
struct Student s1;//结构体变量
struct Student *p = &s1;//结构体指针变量
s1.id = 1001;
//由于 s1.name 表示地址,所以不能直接赋值
strcpy(s1.name, "xiaoming");
s1.score = 100.0;
printf("id = %d \n", s1.id);
printf("name = %s \n", s1.name);
printf("score = %f \n", s1.score);
(*p).id = 1002;
p->id = 1003;
strcpy(p->name, "xiaohong");
p->score = 99.9;
printf("id = %d \n", p->id);
printf("name = %s \n", p->name);
printf("score = %f \n", p->score);
return 0;
}
`
联合体和枚举
`
#include<stdio.h>
//结构体类型中每个成员都有自己的一块内存空间
struct St{
int a;
float b;
long c;
};
//联合体类型中所有成员共享一块内存空间
union Un{
int a;
float b;
long c;
};
//枚举表示一系列整形常量的集合
enum En{
One = 10,
Two,
Three
};
int main(){
struct St s;
union Un u;
enum En e1, e2, e3;
s.a = 10;
s.b = 20.0;
s.c = 30;
u.a = 10;
u.b = 20.0;
e1 = One;
e2 = Two;
e3 = Three;
printf("sizeof(struct St) = %d\n", sizeof(struct St));
printf("sizeof(union Un) = %d\n", sizeof(union Un));
printf("s.a = %d \n", s.a);
printf("s.b = %f \n", s.b);
printf("s.c = %d \n", s.c);
printf("&u.a = %p \n", &u.a);
printf("&u.b = %p \n", &u.b);
printf("u.b = %f \n", u.b);
printf("e1 = %d \n", e1);
printf("e2 = %d \n", e2);
printf("e3 = %d \n", e3);
return 0;
}
`