博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c语言中的结构体指针类型的cast
阅读量:4635 次
发布时间:2019-06-09

本文共 2359 字,大约阅读时间需要 7 分钟。

1.我们在c语言中会经常碰到强制类型转换。

在这,我介绍一种结构pointer类型转换,但是有前提(有点类似于c++中的继承中的子父对象的cast)。

简单的介绍一下:

 首先我们要知道一个结构的指针,并且 在这个结构体中,第一个结构成员必须也是一个结构体(最好是结构体类型).

那么我们可以这个结构体指针转换为指向这个结构体中第一个成员结构体的指针。

直接看代码:

************************************ /*              struct transform for struct point                                                                                             2  *              author lkk  3  *              time  2015-5-2  4  *              inclcude a struct point  5  */  6 /*  7  *  first a main struct vx_image( the key to include sub-struct) point  8  *  we need transform the struct type to place first in the main struct  9  *  some other struct  10  * 11  */ 12   13 #include 
14 // define vx_ref 15 typedef struct _vx_ref{ 16 int a; 17 }vx_ref_t; 18 typedef struct _vx_ref *vx_ref; 19 //define vx_scale 20 typedef struct _vx_scale{ 21 int ab; 22 }vx_scale_t; 23 typedef struct _vx_scale *vx_scale; 24 //define vx_image include the two struct vx_ref vx_scale 25 typedef struct _vx_image { 26 vx_ref_t ab; 27 vx_scale_t ac; 28 int b; 29 }vx_image_t; 30 typedef struct _vx_image *vx_image; 31 //the main 32 void main() 33 { 34 vx_image a; //define a point to vx_image pointer 35 a->ab.a = 1;// put to assignment of sub_struct 36 a->ac.ab = 2; 37 printf("********the old value*********\n"); 38 printf("the main struct value is %d %d:\n",a->ab.a,a->ac.ab); 39 printf("the transform first structure\n"); 40 vx_ref p = (vx_ref)a;// make the main struct pointer point to sub_strcut 41 // printf("the transform second structure\n"); 42 printf("the is %d\n",p->a);//output 43 // printf("we try\n"); 44 // vx_scale q = (vx_scale)a; 45 // printf("the is %d ",a->ab);//output 46 47 } 48 // the conclusion 49 //in the main struct include some sub_strcut 50 //we can use first sub_struct pointer to cast(强制转换) the main structure pointer 51 // example : sub_strcut pointer = (sub_struct) (the main structure pointer) 52 //so we get sub_struct pointer. 53 //only by first point

  运行结果:

********the old value*********

the main struct value is 1 2:
the transform first structure
the is 1

刚好和自己的想法是一样的。

转载于:https://www.cnblogs.com/lkkandsyf/p/4472547.html

你可能感兴趣的文章
第一次软件工程作业(改进版)
查看>>
WPF的图片操作效果(一):RenderTransform
查看>>
网络流24题-飞行员配对方案问题
查看>>
Jenkins 2.16.3默认没有Launch agent via Java Web Start,如何配置使用
查看>>
Excel的数据分析—排位与百分比
查看>>
讯飞语音识别Android-Demo
查看>>
引入css的四种方式
查看>>
Mysql蠕虫复制
查看>>
centos7+ansible自动化工具使用
查看>>
iOS开发UI篇—transframe属性(形变)
查看>>
3月7日 ArrayList集合
查看>>
正则替换
查看>>
jsp 环境配置记录
查看>>
本地视频播放黑屏,有声音
查看>>
Python3-Cookbook总结 - 第一章:数据结构和算法
查看>>
Python03
查看>>
LOJ 2537 「PKUWC2018」Minimax
查看>>
使用java中replaceAll方法替换字符串中的反斜杠
查看>>
Android初学第36天
查看>>
Some configure
查看>>