指针(五)
- 指针数组
- 结构体指针
一、指针数组
1)关于指针数组
一个数组,里面存储的是指针(也就是带*的类型)
指针数组:
1 char* arr[5] = {0}; //用0填充数组
2
3 arr[0] = (char*)1;
4 arr[1] = (char*)2;
5 arr[2] = (char*)3;
6 arr[3] = (char*)4;
7 arr[4] = (char*)5;
8
9 char a1 = 'A';
10 char a2 = 'B';
11 char a3 = 'C';
12 char a4 = 'D';
13 char a5 = 'E';
14
15 char* p1 = &a1;
16 char* p2 = &a2;
17 char* p3 = &a3;
18 char* p4 = &a4;
19 char* p5 = &a5;
20
21 char* arr[5] = {p1,p2,p3,p4,p5};
指针数组在内存中存储的方式:
2)指针数组的用法
1】字符串放在常量区,常量区的字符串地址存入指针数组
1 char* p1 = "if"; 2 char* p2 = "for"; 3 char* p3 = "while"; 4 char* p4 = "switch"; 5 6 char* keyword[] = {p1,p2,p3,p4};
2】和上一种方式的效果一样,实际上指针数组存放的是常量区字符串的地址;
1 char* keyword[] = 2 { 3 "if", 4 "for", 5 "while", 6 "switch" 7 };
二、结构体指针
一个结构类型带一个*;
1)特征
和基础数据类型的指针特性一样:
- 可以++、--;
- +整数、-整数,并且结果为加减整数乘结构体宽度;
- 两个相同的结构体指针可以相减,结果为int型(相减结果/结构体宽度);
- 相同的结构体指针可以比较大小;
ps:也可以将普通指针强转成结构体指针;但是访问数据时是按结构体的方式来读,读取的数据可能不正确或者无法访问;
2)用结构体指针操作结构体
1 sturct Student{
2 int a;
3 int b;
4 int c;
5 };
6
7 //创建结构体
8 Student s;
9 s.a = 10;
10 s.b = 20;
11 s.c = 30;
12
13 //声明结构体指针
14 Student* ps;
15
16 //为结构体指针赋值
17 ps = &s;
18
19 //通过指针读取数据
20 printf("%d\n",ps->a); //用“->”符号访问结构体内容;
21
22 //通过指针修改数据
23 ps->a = 100;
24 printf("%d\n",ps->a);
3.实例
代码:
1 #include "stdafx.h"
2
3 typedef struct Player{
4 int id;
5 int level;
6 } st;
练习:
从中找id=1,level=8的结构体数据
1 char arr[100]={
2 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x07,0x09,
3 0x00,0x20,0x10,0x03,0x03,0x0C,0x00,0x00,0x44,0x00,
4 0x00,0x33,0x01,0x00,0x00,0x08,0x00,0x00,0x00,0x00,
5 0x00,0x00,0x00,0x02,0x64,0x00,0x00,0x00,0xAA,0x00,
6 0x00,0x00,0x64,0x01,0x00,0x00,0x00,0x08,0x00,0x00,
7 0x00,0x00,0x02,0x00,0x74,0x0F,0x41,0x00,0x00,0x00,
8 0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x0A,0x00,
9 0x00,0x02,0x57,0x4F,0x57,0x00,0x06,0x08,0x00,0x00,
10 0x00,0x00,0x00,0x64,0x00,0x0F,0x00,0x00,0x0D,0x00,
11 0x00,0x00,0x23,0x00,0x00,0x64,0x00,0x00,0x64,0x00
12 };
13
14 void fun(){
15 for(int i=0;i<=100-8;i++){
16 st* s = (st*)(arr+i); //将char*强转为结构体指针
17 if(s->id==1 && s->level==8){
18 printf("%d ->%x",i,arr+i);
19 }
20 }
21 }
22
23 int main(int argc, char* argv[])
24 {
25 fun();
26 getchar();
27 return 0;
28 }