c語言結構體指針的高級用法,向上向下強轉

typedef unsigned int  u32;
typedef unsigned short u16;
typedef unsigned char  u8;


#include "string.h"
#include "stdio.h"
#include "stdlib.h"

//原理:結構體指針內存地址是連續的
typedef struct{
    int name;
    int age;
    int year;
}HansenTest_t;

int main(void)
{
	HansenTest_t *Hansen = (HansenTest_t*)malloc(sizeof(HansenTest_t));
	Hansen->name = 10;
	Hansen->age = 18;
	Hansen->year = 101;
	
	//獲取其中一個值向下強轉
	int *p = (int*)Hansen;
	printf("%d\n",*p);
	
	//根據P的首地址強制轉換獲得其他成員變量的值 向上強轉
	HansenTest_t *p2 = (HansenTest_t*)p;
	printf("%d,%d,%d",p2->name,p2->age,p2->year);
}

//C語言在線測試網站
//http://www.dooccn.com/c/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章