C 語言中結構體強制轉換--實驗

對於C語言中結構體強制轉換作了以下實驗, 或許能夠解惑一些問題ios

對於結構體, 我理解的屬性有: 成員的順序, 成員的類型,成員的個數,成員名稱,這些屬性在對結構操做的時候會有一些影響, 好比結構體的對齊, 結構體的強制轉換.測試

處於對上述描述的理解,作出以下測試工做,spa

以結構強制轉換實現爲目的, 實現順序,類型,個數在不一樣的組合下,轉換的結果,code

一 :  成員順序&& 成員類型內存

#include <iostream>
using namespace std;

typedef struct  _foo{
	short a;
	int b;
}foo;


typedef struct _bar
{
	int a;
	short b;
}bar;

int main()
{

	foo f={1,2};
	bar *pbar = (bar*)&f;

	printf("%d\r\n",pbar->a);
	printf("%d\r\n",pbar->b);
	return 0;
}

/* 
output:
-859045887
2
*/
#include <iostream>
using namespace std;

typedef struct  _foo{
	char* a;
	int b;
}foo;


typedef struct _bar
{
	short a;
	long long  b;
}bar;

int main()
{

	foo f={"zhang",2};
	bar* pbar = (bar*)&f;

	printf("%d\r\n",pbar->a);
	printf("%d\r\n",pbar->b);

	return 0;
}
/*
output:
-13200
-858993460
*/

經過測試,在成員的順序不一樣的時候, 若是進行強制的轉換,結果是不可預知的,危險.io

在成員類型徹底不一致的狀況下,  結果是不能夠預計的.class

// 成員名稱stream

#include <iostream>
using namespace std;

typedef struct  _foo{
	short a;
	int b;
}foo;


typedef struct _bar
{
	short b;
	int a;
}bar;

int main()
{

	foo f={1,2};
	bar* pbar = (bar*)&f;

	printf("%d\r\n",pbar->b);
	printf("%d\r\n",pbar->a);

	return 0;
}
/*
output:
1
2
*/

測試結論: 結構體強制轉換時,與成員的名稱沒有關係,在順序保持一致的狀況下.gc

// 成員長度數據

#include <iostream>
using namespace std;

typedef struct _foo
{
	int a;
	char *s;
}foo;

typedef struct _bar
{
	int a;
	char* s;
	int b;
}bar;

int main()
{

	foo f={1,"zhangchao"};
	bar* pbar = (bar*)&f;

	printf("%d\r\n",pbar->a);


	while(*(pbar->s) != '\0')
	{
		printf("%c",*(pbar->s));
		(pbar->s)++;
	}
	printf("\r\n");

	printf("%d\r\n",pbar->b);

	return 0;
}

/*
output:
1
zhangchao
-858993460
*/

在屬性保持一致的狀況下, 多的成員類型的值不可預計.

// 成員裁剪,

#include <iostream>
using namespace std;

typedef struct _foo
{
	int a;
	char *s;
}foo;

typedef struct _bar
{
	int a;
	char* s;
	int b;
}bar;

int main()
{

	bar  f={1,"zhangchao",2};
	foo* pbar = (foo*)&f;

	printf("%d\r\n",pbar->a);


	while(*(pbar->s) != '\0')
	{
		printf("%c",*(pbar->s));
		(pbar->s)++;
	}
	printf("\r\n");
		
	// 以下的訪問操做是錯誤的, 該語句僅僅是爲了測試.
	//printf("%d\r\n",pbar->b);

	return 0;
}

在多成員結構體轉換爲少成員結構體時,注意不要訪問不存在的成員;

經過如上的測試, 若是要進行結構體的強制轉換, 須要考慮如上的因素. 

若是測試遺漏的,請指正,謝謝.

更新:

1  上述的測試代碼只看到了表面 的現象, 結論是: 不一樣的的結構體間互相的轉換, 最終的結果是截斷或是補充。

2  轉換的實質是 : 按照數據在內存中的位置,逐個給左值中的成員賦值。 特別注意,結構體的對齊問題。

因此會出現讀取到的數據是異常的

相關文章
相關標籤/搜索