【问题标题】:Why is the output "0x7ffffcf9a010"? [duplicate]为什么输出“0x7ffffcf9a010”? [复制]
【发布时间】:2021-10-29 17:25:02
【问题描述】:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
    cars[0] = "Opel";
    cout << cars;
    return 0;
}

为什么我输出时返回0x7ffffcf9a010?

【问题讨论】:

  • cout 不知道如何打印数组。使用循环单独打印每个字符串。
  • 显示数组第一个成员的内存地址
  • 分配cars[0] = "Opel";的目的是什么?输出cars时你期望什么?
  • @TedLyngmo 在通过 w3 学校学习时,我通过了这段代码,当我尝试编辑它时,我想知道输出,但它输出了一些指针变量,所以我有点困惑,但是的,现在我明白为什么会这样了,在此先感谢:)
  • @HolyBlackCat 哦,很好!

标签: c++


【解决方案1】:

是的,它会输出,你看到的奇怪数字是数组第一个元素的起始地址,汽车被隐式转换为指针。就其本身而言,它是一个数组而不是一个指针。

你想这样做,

#include <iostream>
#include <string>
using namespace std;

int main() {
    string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
    cars[0] = "Opel";
    //cout << cars[0]; // To print the first element
    for(int i = 0; i < 4; i++)
    {
        // To print all the elements one by one with a new line in between each element
        cout<<cars[i] << '\n';
    }

    return 0;
}

【讨论】:

  • cars 被隐式转换为指针。它本身是一个数组而不是一个指针。
  • "cars 是指向数组中第一个字符串的指针" - 不,它不是指针。它是一个数组,句号。更准确地说,它 衰减 为指向第一个字符串的指针。与作为指针不太一样。
  • 是的,很抱歉措辞不准确,我已经相应地更正了。
  • 是的,所以这意味着当我使用 cout 输出时,它总是会返回一个指针变量,我必须使用循环而不是使用 cout 来获取列表。
  • 是的,你必须这样做。你也可以做 cout
【解决方案2】:

它输出数组的第一个元素(0 索引)的十六进制地址。由于数组是一种数据结构,因此它会输出其地址。

要更正代码,您需要这样做:

#include <iostream>
#include <string>


int main() {
    std::string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
    cars[0] = "Opel";
    
    char string1[100]={"C-style string."};
    std::cout << *cars<<"\n";
    
    
    std::cout<<string1; // does not show hexadecimal address but why?
    return 0;
}

现在此代码将根据您的需要输出“欧宝”。汽车旁边的小星号称为间接运算符。它用于访问指针指向的值。您的困惑可能来自 char 数组,该数组可以使用 std::cout 一次性输出,但 char 数组是规则的一个例外,字符串数组不一样。 注意(在现代 C++ 编程中最好使用 std::array 和 std::vector,而不是老式的数组。)

【讨论】:

  • 好的,谢谢 :) ,但我并没有真正使用 std::array ,因为有时我会感到困惑,所以是的......
【解决方案3】:

输出原始数组的名称会返回字符串数组的首地址,也就是首元素地址。这是 std::string 和 int 原始数组的示例。

#include<iostream>

int main() {
    std::string str[] = {"This", "is", "a", "string"};
    std::cout << str << std::endl;    //output 0xc3585ff5b0

    int arr[] = {1, 2, 3, 4, 5};
    std::cout << arr << std::endl;    //output 0xc3585ff590
    return 0;
}

【讨论】:

  • 感谢指出我的错误,答案已更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
  • 1970-01-01
  • 2014-11-20
相关资源
最近更新 更多