我對將結構指針去結構化爲 結構變量有點混淆。解引用指向結構變量的結構指針
如果我用一個例子證明我的問題,那將會很好。
所以我在這裏:
struct my_struct{
int num1;
int num2;
}tmp_struct;
void Display_struct(void * dest_var){
struct my_struct struct_ptr;
struct_ptr = *((struct my_struct *)dest_var);
printf("%d\t%d\n",struct_ptr.num1,struct_ptr.num2);
}
int main()
{
tmp_struct.num1 = 100;
tmp_struct.num2 = 150;
Display_struct(&tmp_struct);
return 0;
}
現在,當我運行這個例子我能得到的代碼在一個非常乾淨的方式進行編譯,並輸出是正確的。
但是我不能夠得到是這個結構指針引用到結構變量的正確的方式,因爲我們在其他簡單 數據類型的情況下,這樣做:
int example_num;
void Display_struct(void * dest_var){
int example_num_ptr;
example_num_ptr = *((int *)dest_var);
printf("%d\t%d\n",struct_ptr.num1,struct_ptr.num2);
}
int main()
{
example_num = 100;
Display_struct(&example_num);
return 0;
}
這裏我們可以將int指針取消引用到int變量,因爲它是一個簡單的數據類型,但在我看來,我們不能像結構變量那樣以類似的方式取消引用結構指針,因爲它不是簡單的數據類型,而是複雜的數據類型或數據結構。
請幫我解決這個背後的概念。
爲什麼你不能取消引用指針結構?在一個指針中,你不能訪問底層對象的地方是什麼? –
你的意思是這樣的:https://ideone.com/lduzh0? – mch
這裏的實際問題是什麼?順便說一句第二個例子是錯誤的,你嘗試printf'struct_ptr.num1',但在第二個例子中沒有'struct_ptr'。 –