代码之家  ›  专栏  ›  技术社区  ›  user2138149

为什么我不能获取包含多个元素的结构体中某些元素的地址?[副本]

  •  1
  • user2138149  · 技术社区  · 4 月前

    为什么我不能记下元素的地址 a c 在这个 struct ?

    #include <iostream>
    
    struct Silly {
        char a;
        unsigned short b;
        char c;
        double d;
    };
    
    int main() {
    
        auto p_silly = new Silly[2];
    
        std::cout << "address of a: " << &(p_silly[0].a) << std::endl;
        std::cout << "address of b: " << &(p_silly[0].b) << std::endl;
        std::cout << "address of c: " << &(p_silly[0].c) << std::endl;
        std::cout << "address of d: " << &(p_silly[0].d) << std::endl;
    
        delete[] p_silly;
    }
    

    输出:

    address of a: 
    address of b: 0x61620d70c6c2
    address of c: 
    address of d: 0x61620d70c6c8
    

    编译依据:

    g++ main.cpp -o main -std=c++23
    
    1 回复  |  直到 4 月前
        1
  •  0
  •   Dave S    4 月前

    这是因为这些是字符——当你拿到地址时,你是在通过 char* iostreams有一个重载,它将char*视为以NUL结尾的字符串(这是C传递它们的方式),而不是地址,并将其打印为字符串。

    推荐文章