經過內置變量偏移地址訪問結構體變量

#pragma pack(1)//一字節對其方式

#include<stdio.h>
#include<stddef.h>
#include<string.h>

struct node_t{
 int offset[10];
 char a[9];
 int b;
 int c;
};

int main()
{
	struct node_t node;
	size_t size;
	//方式1
/*經過函數庫的offsetof()宏來獲取成員變量的偏移量*/
	size = offsetof(struct node_t,c);
	printf("method one:%d\n",size);
	//思路:(結構體成員變量c的地址) 減去 (結構體起始地址)獲取偏移量
	size = (unsigned long)(&(node.c)) - (unsigned long)(&node);
	printf("method two:%d\n",size);
	
	int *p_c;//成員變量c的指針
	char *p_a;//成員變量a的指針
//經過偏移地址獲取成員變量c的地址
	p_c = (int*)((unsigned long)(&node)+sizeof(char)*9 +sizeof(int) + sizeof(int)*10); 
//設置其值爲12
	*p_c = 12;
//正常方式訪問變量,檢測是否設置成功
	printf("node_c = %d\n",node.c);
//獲取成員變量a的地址
	p_a = (char*)((unsigned long)(&node)+sizeof(int)*10);
	strcpy(p_a,"hello");
//檢測是否設置成功
	printf("p_a = %s\n",node.a);
//方式2
//(struct node_t *)0 是騙編譯器說有一個指向類(或結構)node_t的指針,其地址值0,
/*offset宏的原型 #define offsetof(s, m)   (size_t)&(((s *)0)->m)
s是一個結構名,它有一個名爲m的成員(s和m 是宏offsetof的形參,它實際是返回結構s的成員m的偏移地址
(s *)0 是騙編譯器說有一個指向類(或結構)s的指針,其地址值0 
&((s *)0)->m   是要取得類s中成員變量m的地址. 因基址爲0,這時m的地址固然就是m在s中的偏移
最後轉換size_t 型,即unsigned int。
*/

	size = (unsigned long)&(((struct node_t *)0)->c);
	printf("method two:%d\n",size);
	return 0;
}
相關文章
相關標籤/搜索