2

Keep in mind that my knowledge of pointers is quite small, as I just started learning about them.

While I was messing around in C++, I wrote this small bit of code thinking it would just print out the address of each character in the string

#include <iostream>

using namespace std;

string a = "Hello, World!";

int main() {
    for(int i=0; i<a.length();i++) {
        cout << &a[i] << endl;
    }
    return 0;
}

When I compiled and ran this, however, it resulted in it printing as if the string moved to the left.enter image description here

It just doesn't make sense why when it uses &, which I thought would retrieve the address, would instead get the rest of the string.

kittrz
  • 81
  • 1
  • 3
  • 13

2 Answers2

3

As said in the comment, &a[i] is a pointer to a char, and << operator will print null terminated string starting from this character, not its address. So if you want to print the address, you must cast it to void *, as follow :

#include <iostream>
using namespace std;

string a = "Hello, World!";

int main() {
    for(int i=0; i<a.length();i++) {
        cout << (void *)&a[i] << endl; //cast to (void *) to get the address
    }
    return 0;
}
souki
  • 1,305
  • 4
  • 23
  • 39
1

string subscript ([]) operator returns char. So & operation returns a pointer to char. And cout operator<< has an overloading for it, which consider it should print out the parameter as a c-string. You should cast it to void* so cout wouldn't think it is a string.

(void*)&a[i]
NuPagadi
  • 1,410
  • 1
  • 11
  • 31