cout输出char*使用踩坑

cout输出char*使用踩坑

首先看下面代码的执行输出:

#include 
#include 
#include 

struct Foo
{
    char a;
    int b;
    short c;
    alignas(128) long long d;
};

int main()
{
    Foo foo;
    std::cout << "sizeof(Foo): "<< sizeof(foo) << '\n';
    std::cout << "&Foo: " <<  std::hex << &foo << '\n';
    std::cout << "&Foo.a: " << std::hex << &foo.a << '\n';
    std::cout << "&Foo.b: " << std::hex << &foo.b << '\n';
    std::cout << "&Foo.c: " << std::hex << &foo.c << '\n';
    std::cout << "&Foo.d: " << std::hex << &foo.d << '\n';
    foo = {'A', 10, 2, 15};
    std::cout << "sizeof(Foo): "<< std::dec << sizeof(foo) << '\n';
    std::cout << "&Foo: " <<  std::hex << &foo << '\n';
    std::cout << "&Foo.a: " << std::hex << &foo.a << '\n';
    printf("&Foo.a: %p\n", &foo.a);
    std::cout << "&Foo.b: " << std::hex << &foo.b << '\n';
    std::cout << "&Foo.c: " << std::hex << &foo.c << '\n';
    std::cout << "&Foo.d: " << std::hex << &foo.d << '\n';
    return 0;
}

输出结果:

➜  Test ./a.out 
sizeof(Foo): 256
&Foo: 0x7ffcd81f8900
&Foo.a:   컞
&Foo.b: 0x7ffcd81f8904
&Foo.c: 0x7ffcd81f8908
&Foo.d: 0x7ffcd81f8980
sizeof(Foo): 256
&Foo: 0x7ffcd81f8900
&Foo.a: A 

&Foo.a: 0x7ffcd81f8900
&Foo.b: 0x7ffcd81f8904
&Foo.c: 0x7ffcd81f8908
&Foo.d: 0x7ffcd81f8980
➜  Test ./a.out
sizeof(Foo): 256
&Foo: 0x7ffcc3f20e80
&Foo.a: 
&Foo.b: 0x7ffcc3f20e84
&Foo.c: 0x7ffcc3f20e88
&Foo.d: 0x7ffcc3f20f00
sizeof(Foo): 256
&Foo: 0x7ffcc3f20e80
&Foo.a: A`
&Foo.a: 0x7ffcc3f20e80
&Foo.b: 0x7ffcc3f20e84
&Foo.c: 0x7ffcc3f20e88
&Foo.d: 0x7ffcc3f20f00

分析:

  1. 第一次&Foo.a: 컞打印乱码,是因为结构体没有初始化
  2. 第二次&Foo.a: A打印A, 没有按照预期输出地址,采用printf可以输出地址。原因: C++里cout太自作聪明了(<<运算符重载),为了省去我们循环输出字符的麻烦,cout<<&Foo.a;被翻译为输出&Foo.a指向的字符串值。

解决办法:

  • way1: 采用printf进行格式化输出

  • way2:

    void *p = &foo.a;
    std::cout << "p = &Foo.a: " << std::hex << p << '\n';
    

你可能感兴趣的:(C/C++,c++,输出流)