指针数组和结构体指针

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


下一篇:C语言库函数篇1:sscanf用法