【发布时间】:2019-11-15 23:19:22
【问题描述】:
我有一个函数 int_make,我用它来将 int 转换为 void 指针:
void* int_make(int id_num){
int* id_ptr = malloc(sizeof(int));
id_ptr = &id_num;
void* id = id_ptr;
return id;}
我主要通过以下方式对此进行测试
void * num_ptr = int_make(889);
printFunction(num_ptr);
printFunction(num_ptr) 将指针转换为 int* 指针,然后取消引用它
void printFunction(void * num_ptr){
printf("*(int*)num_ptr is %d\n", *(int*)num_ptr);}
我得到了预期的输出
*(int*)num_ptr is 889
一切都好,直到我调用不同的函数 testD,(忽略未使用的参数,所有非错误代码都已删除)
void testD(void* ID, void* name, void* address, void* phone, struct hashtable* hashtable){
printf("*(int*)phone is %d\n", *(int*)phone);}
main 中的调用:
void* phone= int_make(939209);
testD(id,name,addy,phone, table);
我得到令人困惑的结果:
*(int)phone is 21985
这个数字(21985)每次我执行代码时都不一样,所以它一定是一个内存位置,虽然我不知道为什么我的策略(void* to int)在889示例(以及许多其他测试,每个重播几次)而不是这次。
【问题讨论】: