Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of each character of std::string

I tried to print the address of each character of std::string. But I amn't understanding what is happening internally with std::string that is resulting this output while for the array it is giving the address as I expected. Could someone please explain what is going on?

#include <iostream>
#include <string>

using namespace std;

int main(){

   string str = "Hello";
   int a[] = {1,2,3,4,5};

   for( int i=0; i<str.length(); ++i )
      cout << &str[i] << endl;

   cout << "**************" << endl;

   for( int i=0; i<5; ++i )
      cout << &a[i] << endl;

    return 0;
}

Output:

Hello
ello
llo
lo
o
**************
0x7fff5fbff950
0x7fff5fbff954
0x7fff5fbff958
0x7fff5fbff95c
0x7fff5fbff960
like image 217
Mahesh Avatar asked Sep 16 '11 06:09

Mahesh


People also ask

How do you reference a character in a string C++?

You can access the characters in a string by referring to its index number inside square brackets [] .

How do I get individual characters from a string in C++?

C++ at() function is used for accessing individual characters. With this function, character by character can be accessed from the given string.

How do I find a character in a string?

The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search. The strchr() function operates on null-ended strings.

What does std::string () do?

std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.


2 Answers

When a std::ostream tries to print a char* it assumes it's a C-style string.

Cast it to a void* before printing and you will get what you expect:

cout << (void*) &str[i] << endl;
like image 175
mange Avatar answered Nov 15 '22 05:11

mange


or you may use the old printf

printf("\n%x",&s[i]);
like image 29
vivek Avatar answered Nov 15 '22 07:11

vivek