基本指针问题
Basic pointer issue
我最近贴出了一些与指针相关的问题。我试图在这篇文章中把我所遭受的困惑统一起来,所以如果它看起来很熟悉,我很抱歉。问题是-为什么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
相关文章:
- 关于 c++ 函数中指针赋值的简单问题
- 链表指针问题
- C++ 关于指针取消引用的技术问题
- C++中的指针和常量问题不大
- 包含矢量指针的结构的内存释放问题
- 指针问题:从不兼容的类型"int"分配给"int *"
- 将字节数组转换为带有字节序问题的指针
- 关于如何使用指向主窗口的指针的 QT 问题
- 当成员值从指针更改为非指针时,C++常量问题
- 为什么循环会导致指针出现问题?
- 使用指针计算堆栈问题的大 O 表示法
- 构造函数 (C++) 中的 char 指针参数存在问题
- 指向包含对齐 C 结构C++类的 C 指针的对齐问题
- 涉及指针和手动实现的矩阵类的问题
- 从基指针到派生的强制转换问题
- 迭代器的指针操作问题
- 64 位迁移问题:指针更改
- C++模板使用问题指针
- 跳到C++第13章练习问题4-指针
- 用std::pair数组初始化std::map问题(指针错误?)