基本指针问题

Basic pointer issue

本文关键字:问题 指针      更新时间:2023-10-16

我最近贴出了一些与指针相关的问题。我试图在这篇文章中把我所遭受的困惑统一起来,所以如果它看起来很熟悉,我很抱歉。问题是-为什么funky()输出字符串而funkier()输出地址?我的逻辑告诉我,后者是我所期望的。或者这只是std::cout处理事情的方式?

我注意到printf的行为方式相同。

#include <iostream>
using namespace std;
void funky(const char* a);
void funkier(char* a[]);
int main() {
    const char* y = "message";
    funky(y);
    char* z[3];
    z[0] = "one";
    z[1] = "two";
    z[2] = "three";
    funkier(z);
    cin.get();
    return 0;
}
void funky(const char* a) {
    cout << a << endl; // prints the string.
}
void funkier(char* a[]) {
    cout << a << endl; // prints the address.
}

operator<< for std::ostream为许多不同类型的右操作数重载。

如果第二个操作数是const char*,则将其解释为以空结束的字符串并打印。

如果第二个操作数是const void*,则打印为地址。

还有许多其他的重载,但这些在这里不相关。

funky()调用使用第一个重载。

但是funkier参数实际上是一个char**,它既不是上面的任何一个。但它可转换为const void*,而不是const char*,因此使用了第二个重载。

小心printf() !这是一个C函数,它不检测参数的类型。它期望您为每个参数传递正确的%s%p或其他参数。如果你使用了错误的字母,或者传递了错误的参数类型,你可能会得到未定义行为

char *x = "a";
printf("%s", x); //prints x as string
printf("%p", x); //prints x as pointer
printf("%d", x); //Undefined Behaviour!!!
printf("%d", (int)x); //prints the pointer value as an integer, if it fits