C offsetof

void test4()
{

	struct student {
		char a;
		int b;
	};

	struct student stu = {1,1};
	struct student* p = &stu;


	printf("addr is :%d\r\n", (char*)&(stu.b) - (char*)&(stu.a));
	printf("addr is :%d\r\n", (char*)&(p->b) - (char*)&(p->a));
	printf("addr is :%d\r\n", (int*)&(p->b) - (int*)&(p->a));      # 這個的輸出爲1, 須要理解步進的含義
	printf("addr is :%d\r\n", (int)&(p->b) - (int)&(p->a));
	printf("addr is :%d\r\n", (int)&(p->b) - (int)p);
	//printf("addr is :%d\r\n", (void*)&(p->b) - (void*)&(p->a)); #這個會提示類型未定義.
	printf("addr is :%d\r\n", offsetof(struct student,b));        #藉助 <stddef.h>

}

經過手動的方式去計算, 結構體成員在結構體中的偏移量是多少, 推薦使用 char* 強轉(在沒有使用底層的api 時)api

 

void test5()
{
	
	struct person {
		char a;
		int b;
	};


	struct student
	{
		char a;
		int b;
		struct person p;
	};

	struct student stu = { 1,2,2,3 };
	
	int offset1 = offsetof(struct student, p);
	int offset2 = offsetof(struct person, b);

	printf("%d\r\n", *(int*)((char*)&stu+offset1+offset2));
	printf("%d\r\n", ((struct person*)((char*)&stu + offset1))->b);
}
相關文章
相關標籤/搜索