我的指向字符串第一个字符的指针的地址为什么不等于字符串的地址?

huangapple go评论153阅读模式
英文:

Why is the address of my pointer to first char of string != string address?

问题

为什么如果我从字符串"s"和保存在指针"p"中的字符串的第一个字符打印出来,地址会不同?它们不应该是相同的吗?我得到了相同的字符,但地址不同。

#include <stdio.h>
#include

int main()
{
std::string s = "hello";
char *p = &s[0];
printf("%p\n", s);
printf("%p\n", p);

printf("%c\n", s[0]);
printf("%c\n", *p);

}


<details>
<summary>英文:</summary>

Why is the address different if i print it from string &quot;s&quot; and from the first char of the string, saved in the pointer &quot;p&quot;? Should it not be the same? I get the same char but the address is different.

#include <stdio.h>
#include <string>

int main()
{
std::string s = "hello";
char *p = &s[0];
printf("%p\n", s);
printf("%p\n", p);

printf(&quot;%c\n&quot;, s[0]);
printf(&quot;%c\n&quot;, *p);

}


</details>


# 答案1
**得分**: 1

在C++中,std::string是一个包含数据的对象(或更可能是一个指向数据的指针),因此对象和它包含的数据位于不同的位置。

<details>
<summary>英文:</summary>

You might be thinking of plain C strings, where your pointers would match.  

In a C++, the std::string is an object that contains the data (or more likely a pointer to it), so the object and the data it contains will be located in different places.

</details>



huangapple
  • 本文由 发表于 2023年8月11日 01:32:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878068.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定