第一个字符串元素的地址产生意外结果

address of first string element yields unexpected result

本文关键字:意外 结果 地址 字符串 元素 第一个      更新时间:2023-10-16

目标是编写一个函数,该函数输出字符串的第一个元素的地址,该元素等于字符,但是我对结果感到困惑。

用字符串评估该函数,该字符串首先包含上述字符时,我在字符串开始的地址和第一个元素的地址之间得到了2个字节的差异。例如。0x7ffe559716d00x7ffe559716e0。地址不应该一样吗?

#include <iostream>
#include <string>
using namespace std;
const char* first_char(const char* str, const char ch)
{
    for (int i = 0; str[i] != 0; ++i)
    {
        if (str[i] == ch)
            return (i+str);
    }
    return 0;
}
int main() {
    string str1 = "jasdfgjhk";
    const char ch1 = 'j';
    cout << &str1 << endl;
    //should be the same address as above?
    cout << (void*)first_char(&str1[0], ch1) << endl;
    return 0;
}

更改以下内容:

cout << &str1 << endl;

cout << (void*)str1.data() << endl;

您将获得与功能返回的地址相同的地址。

原因是 std::string不仅是字符数组,而且是一个类,它具有一个数组的数据成员,并存储了字符串的字符。

通过使用data(),您将获得该数组。当您打印其地址时,它为您提供了数组的实际地址,以及

之前的班级的实际地址

请注意

&str

是"字符串"对象的起始地址。字符串对象不是字符串本身。它包含一个指向字符串本身的(隐藏的)动态指针。因此,通过上面,您会得到"东西",例如指向字符串指针的指针。

但是:

&str1[0]

您确实得到了指向字符串中第一个字符的指针。