c語言中的結構體指針類型的cast


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 <stdio.h>
 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

剛好和自己的想法是一樣的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM