C 函数指针类型转换

C 函数指针类型转换,c,C,我正在尝试下面的代码 int TestMethod(int a, int b) { printf("In TestMethod %d, %d \r\n", a, b); return 0; } int main(void) { void (*ap_cb_function)() = (void(*)())TestMethod; ap_cb_function(); return 0; } 它与gcc编译器配合得很好。这将使用随机值a和b打印输出。这是

我正在尝试下面的代码

int TestMethod(int a, int b)
{
    printf("In TestMethod %d, %d \r\n", a, b);
    return 0;
}


int main(void)
{

    void (*ap_cb_function)() = (void(*)())TestMethod;
    ap_cb_function();

    return 0;
}

它与gcc编译器配合得很好。这将使用随机值a和b打印输出。这是怎么回事?我希望第行出现错误:

void (*ap_cb_function)() = (void(*)())TestMethod;

函数参数在寄存器或堆栈中传递,具体取决于平台的ABI。如果不指定参数,从被调用函数的视图来看,某些随机值(在寄存器或堆栈中)仍然存在。…

“它与gcc编译器配合得很好”编译器没有运行您的程序;它只是为您明确告诉它要做的事情生成代码,不管这有多糟糕。您可以将其强制转换为
int*p
并写入
*p=1如果您愿意,行为也将是未定义的。我已经在上尝试过,并且它也成功运行。因此,这些参数在返回时会错误地弹出。