Home > Net >  Why is the address different?
Why is the address different?

Time:09-01

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 ?

CodePudding user response:

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.

CodePudding user response:

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

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

CodePudding user response:

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

  • Related