在不同编译器上,void** 类型的转换可能会有一些差异。以下是一种常见的解决方法,使用 C 语言的 memcpy
函数进行转换:
#include
#include
int main() {
int num = 10;
void* ptr = #
// 转换为 void**
void** ptr2 = malloc(sizeof(void*));
memcpy(ptr2, &ptr, sizeof(void*));
// 从 void** 转换为 void*
void* ptr3;
memcpy(&ptr3, ptr2, sizeof(void*));
int* numPtr = (int*)ptr3;
printf("num = %d\n", *numPtr);
free(ptr2);
return 0;
}
在这个例子中,我们首先将 int
类型的指针 &num
赋值给 void*
类型的指针 ptr
。然后,我们使用 memcpy
函数将 ptr
的地址复制到 ptr2
中,以便将其转换为 void**
类型。接着,我们再次使用 memcpy
函数将 ptr2
的值复制到 ptr3
中,以将其转换为 void*
类型。最后,我们将 ptr3
强制转换为 int*
类型,并打印出 num
的值。
需要注意的是,这种方法在不同编译器上的行为可能会有所不同,因此在实际使用中应谨慎考虑。最好根据特定编译器的文档或标准来确定正确的转换方法。