void指针强转结构体指针问题

来源:互联网 发布:c语言取绝对值的函数 编辑:程序博客网 时间:2024/06/08 03:32

                         void指针强转结构体指针问题

转自:http://blog.csdn.net/tankai19880619/article/details/8263752

1.程序,test.c

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3.   
  4. typedef unsigned long u32; //64位机器为8字节,32位机器为4字节  
  5. typedef struct my_struct{  
  6.   u32 a;  
  7.   u32 b;  
  8.   u32 c;  
  9. }mystruct;  
  10.   
  11. int main(){  
  12.   void *test;  
  13.   test = NULL;  
  14.   test = malloc(1);  
  15.   printf("test is %lx\n",test);  
  16.   #define GPIO ((mystruct *)(test))  
  17.   GPIO->a = 10;  
  18.   GPIO->b = 20;  
  19.   GPIO->c = 30;  
  20.   printf("(&(GPIO->a)) is %lx\n",(&(GPIO->a)));  
  21.   printf("(&(GPIO->b)) is %lx\n",(&(GPIO->b)));  
  22.   printf("(&(GPIO->c)) is %lx\n",(&(GPIO->c)));  
  23.   printf("GPIO->a is %d\n",GPIO->a);  
  24.   printf("GPIO->b is %d\n",GPIO->b);  
  25.   printf("GPIO->c is %d\n",GPIO->c);  
  26.   free(test);  
  27.   test = NULL;  
  28.   return 0;  
  29. }  
2.编译gcc -o test test.cpp,我的机器是64位ubuntu。

3.结果./test

  1. test is 17f2010  
  2. (&(GPIO->a)) is 17f2010  
  3. (&(GPIO->b)) is 17f2018  
  4. (&(GPIO->c)) is 17f2020  
  5. GPIO->a is 10  
  6. GPIO->b is 20  
  7. GPIO->c is 30 
0 0
原创粉丝点击