首页 > 解决方案 > C++ 将指针传递给期望 void* 的函数以两种不同的方式工作,为什么?

问题描述

最近我偶然发现了我融入这个例子的代码:

void PrintThis (void* input)
{
    std::cout << input << std::endl;
    std::cout << (char*)input << std::endl;
}

int main(void)
{
    char question[] = "Why does it work?";
    PrintThis(question);    // output: address + 'Why does it work?' - expected!
    PrintThis(&question);   // output: address + 'Why does it work?' - unexpected
    char* thisIsDiff = "This is different";
    PrintThis(thisIsDiff);    // output: address + 'This is different' - expected
    PrintThis(&thisIsDiff);   // output: address + rubbish - expected
    return 0;
}

请注意标有意外的行。为什么输出与上面的行相同?为什么当函数参数是 char* 而不是 void 时它甚至无法编译?

标签: c++functionvoidvoid-pointers

解决方案


推荐阅读