您的位置:首页 > 编程语言 > C语言/C++

通过实例深入理解C/C++结构体/类多级指针的使用

2013-09-07 21:27 405 查看
我们先回忆下结构体成员的引用和指针的基础知识:

(1)原理1:

引用结构体变量的成员的一般方式为: 结构体变量名.成员变量名。

其中,“.”被称为成员运算符。它在所有的运算符中优先级最高,因此可以把“结构体变量名.成员变量名”当成一个整体看待。



(2)原理2:

通过指向结构体变量的指针p, 引用其成员的方式为:(*p).成员变量名
或 p->成员变量名


即:定义指向结构体类型变量的指针变量p:

struct [b]结构体类型 *p,
[/b]

则其成员的引用形式为:(1) 指针变量->成员 (2)[b]:(*指针变量).成员变量名[/b]



情形1:

结构体、类的关系如下所示:

A a;

struct A
{
   B* b;
}

struct B

{
   C c;
}

struct C
{
   int *videoInputCnt;
}

假设,我们得到了结构体A变量a,现在在要从a变量中提取整形数据videoInputCnt。

如何做到呢?

我们的获取顺序是:A->B->C->int VideoInputCount.

步骤如下:

(1)获取b成员.

由于b是A类/结构体的B类型的成员指针,且a 非指针,因此获取b成员的方法为:

a.b

(2)获取c成员。

由于b是指针变量,根据原理2,获取c的方法为:

(a.b)->c



或者:

*(a.b).c.

我们这里选择方式1.



(3)获取videoInputCnt.

根据原理1,获取方法为:

*( ( (a.b)->c ).videoInputCnt );



测试代码:

#include <stdio.h>

typedef struct C
{
int *videoInputCnt;
}Ctype;

typedef struct B

{
   Ctype c;
}BType;

typedef struct A
{
   BType* b;
}AType;

 
int main(void)
{
   AType a;
   BType b;
   Ctype c;
   
   int InitialValue;
   InitialValue=5;
    c.videoInputCnt = &InitialValue;
   b.c = c;
   a.b = &b;

  int CntOutput1,CntOutput2;
  CntOutput1=  *( ( (a.b)->c ).videoInputCnt );
  printf("VideoCount is %d..\n", CntOutput1);

  CntOutput2=  * ( (a.b)->c ).videoInputCnt ;
  printf("VideoCount is %d..\n", CntOutput2);

   return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: