第一个字符串元素的地址产生意外结果
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
不仅是字符数组,而且是一个类,它具有一个数组的数据成员,并存储了字符串的字符。
通过使用data()
,您将获得该数组。当您打印其地址时,它为您提供了数组的实际地址,以及
请注意
&str
是"字符串"对象的起始地址。字符串对象不是字符串本身。它包含一个指向字符串本身的(隐藏的)动态指针。因此,通过上面,您会得到"东西",例如指向字符串指针的指针。
但是:
&str1[0]
您确实得到了指向字符串中第一个字符的指针。
相关文章:
- 尝试将字符串/字符转换为整数会产生意外结果
- RapidXML - 代码创建意外结果
- 类中静态函数C++意外结果
- 指针数组中的意外结果
- 使用指针访问数组元素时出现意外结果
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- C++:比较运算符>和字符串文本的意外结果
- 具有意外结果的 C++ 闭包
- yaml-cpp 比较的意外结果
- 每次都出现意外结果
- 在 Qt 中解析嵌套的 JSON 时出现意外结果(数组不存在)
- 如何避免 std::abs 的意外结果?
- 使用嵌套 if 语句的意外结果
- A ^= B ^= A ^= B;C# Visual Studio 中的意外结果
- 逻辑错误,我将获得意外结果
- 在 c++ 中使用异步的意外结果
- 从函数的返回值将元素C++存储到 std::vector 中时出现意外结果
- 执行递增和递减时"cout"链接会产生意外结果
- OpenCL - 内核方法返回意外结果
- C++使用 std::get_time 解析 YYMMDD ISO 8601 日期字符串会得到意外结果