英文:
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 "s" and from the first char of the string, saved in the pointer "p"? 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("%c\n", s[0]);
printf("%c\n", *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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论