Why is the address different?

Viewed 139

I wrote the below code for my understanding of pointers.

#include <cstdio>
#include <iostream>
using namespace std;

int main() {
    string a = "hello";
    const char *st = &a[0];
    printf("%p\n", &st[0]);
    printf("%p\n", &(a[0]));
    printf("%c\n", *st);
    printf("%p", &a);
}

This is the output that I get

0x1265028
0x1265028
h
0x7ffe26a91c40

If my understanding is correct &a should return the address of string, why is the value returned by &a different than the rest ?

3 Answers

A std::string is a C++ object, which internally holds a pointer to an array of chars.

In your code, st is a pointer to the first char in that internal array, while &a is a pointer to the C++ object. They are different things, and therefore the pointer values are also different.

&a is the address of the variable a of type std::string. Since std::string contains a character array of variable length, it must use dynamic allocation and store the real array somewhere else.

However, std::string has many operator overloads. a[0] returns a reference to the first character in a's array, and &a[0] is the address of that character. That's why &st[0] and &a[0] would be the same address, as st also points to the first character in a's array.

0x1265028 - address of first char
0x1265028 - address of first char
h - first char value
0x7ffe26a91c40 - address of std::string object

Related