第一个字符串元素的地址产生意外结果
address of first string element yields unexpected result
目标是编写一个函数,输出等于一个字符的字符串的第一个元素的地址,但是我对结果感到困惑。
当首先使用包含所述字符的字符串评估函数时,我得到字符串开头地址和第一个元素地址之间的 2 个字节的差异。例如。 0x7ffe559716d0
和 0x7ffe559716e0
。
地址不应该一样吗?
#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
不仅仅是一个字符数组,它是一个class,它有一个数据成员是数组,存储的是字符串的字符。
通过使用 data()
,您将获得该数组。当您打印它的地址时,它会为您提供数组的实际地址,以及 class 之前的
请注意
&str
是'string'对象的起始地址。字符串对象不是字符串本身。它包含一个指向字符串本身的(隐藏的)动态指针。所以通过上面你得到 "something" 就像一个指向字符串的指针。
但是有:
&str1[0]
您确实得到了指向字符串中第一个字符的指针。
目标是编写一个函数,输出等于一个字符的字符串的第一个元素的地址,但是我对结果感到困惑。
当首先使用包含所述字符的字符串评估函数时,我得到字符串开头地址和第一个元素地址之间的 2 个字节的差异。例如。 0x7ffe559716d0
和 0x7ffe559716e0
。
地址不应该一样吗?
#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
不仅仅是一个字符数组,它是一个class,它有一个数据成员是数组,存储的是字符串的字符。
通过使用 data()
,您将获得该数组。当您打印它的地址时,它会为您提供数组的实际地址,以及 class 之前的
请注意
&str
是'string'对象的起始地址。字符串对象不是字符串本身。它包含一个指向字符串本身的(隐藏的)动态指针。所以通过上面你得到 "something" 就像一个指向字符串的指针。
但是有:
&str1[0]
您确实得到了指向字符串中第一个字符的指针。