指针
一、指针
int a=3,b=4;
int *p,*q;
p=&a;
*q=3*4;
变量名 | 值(内容) | 指针(地址) |
---|---|---|
a | 3 | 1000 |
b | 4 | 1001 |
… | … | … |
p | 1000 | 2000 |
q |
第四行q没有初始化,不能给内容赋值(所以指针使用前要赋初值,且类型要一致)
二、数组与指针
int a[3]={7,8,9};
int *p;
p=a;//p=&a[0]
p++;//不等价于a++,a不能被修改
p=a;数组名就是指针,存放首元素地址
变量名 | 值(内容) | 地址(指针) |
---|---|---|
a[0] | 7 | 1000 |
a[1] | 8 | 1001 |
a[2] | 9 | 1002 |
… | … | … |
p | 1000 | 2000 |
a | 1000 | 2002 |
a[i]的地址:&a[i],a+i,p+i,&p[i]
a[i]的值:a[i],*(a+i), *(p+i),p[i]
三、结构体
struct student//student为类型名
{
int no;
char name[20];
float score;
}std1,std2={2023010101,"wang",90};//std1,std2为变量名
//std2={2023010101,"wang",90}为结构体变量初始化
也可以写成
struct student
{
int no;
char name[20];
float score;
};
struct student std1,std2={2023010101,"wang",90};
使用typedef优化
tyredef struct student
{
int no;
char name[20];
float score;
}stu;
stu std1,std2={2023010101,"wang",90};
四、成员的访问形式
结构体变量名.成员名
例:scanf("%s",std2.name);
printf("%d",std2.no);
五、结构体数组
struct student
{
int no;
char name[20];
};
struct student stu[3]={{10,"wang"},{11,"li"},{12,"zhang"}};
变量名 | 值(内容) | 地址(指针) |
---|---|---|
stu[0] | 10 | 1000 |
stu[0] | wang | 1000 |
stu[1] | 11 | 1001 |
stu[1] | li | 1001 |
stu[2] | 12 | 1002 |
stu[2] | zhang | 1002 |
六、结构体指针
struct student
{
int no;
char name[20];
};
struct student std1,stu[2];
struct student *sp;
sp=&std1;//访问其成员name用std1.name或sp->name
变量名 | 值(内容) | 地址(指针) |
---|---|---|
std1 | no | 1000 |
std1 | name | 1000 |
stu[0] | no | 1001 |
stu[0] | name | 1001 |
stu[1] | no | 1002 |
stu[1] | name | 1002 |
… | … | … |
sp | 1000 | 2000 |