函式呼叫中的指標轉換
指向 void*
的指標轉換是隱式的,但任何其他指標轉換必須是顯式的。雖然編譯器允許從任何指標到資料型別到任何其他指標到資料型別的顯式轉換,但是通過錯誤鍵入的指標訪問物件是錯誤的並且導致未定義的行為。允許這些的唯一情況是,如果型別是相容的,或者你正在檢視物件的指標是字元型別。
#include <stdio.h>
void func_voidp(void* voidp) {
printf("%s Address of ptr is %p\n", __func__, voidp);
}
/* Structures have same shape, but not same type */
struct struct_a {
int a;
int b;
} data_a;
struct struct_b {
int a;
int b;
} data_b;
void func_struct_b(struct struct_b* bp) {
printf("%s Address of ptr is %p\n", __func__, (void*) bp);
}
int main(void) {
/* Implicit ptr conversion allowed for void* */
func_voidp(&data_a);
/*
* Explicit ptr conversion for other types
*
* Note that here although the have identical definitions,
* the types are not compatible, and that the this call is
* erroneous and leads to undefined behavior on execution.
*/
func_struct_b((struct struct_b*)&data_a);
/* My output shows: */
/* func_charp Address of ptr is 0x601030 */
/* func_voidp Address of ptr is 0x601030 */
/* func_struct_b Address of ptr is 0x601030 */
return 0;
}