1

In C++ could someone clarify

1- In he following code, printing char* is displayed as bunch of random characters, but printing string* is just an integer address? Why so?

int * intptr;
char * charptr;
std::string * stringptr;
float * floatptr;

//printing 
std::cout << intptr << " ,  " << charptr <<  " , " << stringptr << " , " << floatptr << "\n";

output:

  0x7ffeea2f1a60 ,  ���� , 0x7ffeea2f1a48 , 0x1092d13d4

2- charptr is a pointer variable painting to part of memory that contains a character. Just for curiosity, how do you print the address of charptr?

3- While reading different sources, I came across to this: "The different printing is because of the functions (i.e. a const char *) that treat that memory as a sequence of characters". Could someone expand this answer w.r.t the above code?

sepideha
  • 1,669
  • 1
  • 11
  • 14

1 Answers1

2

char* is special with regard to printing. The reason is the historical legacy of C, where strings are represented as arrays of characters. So most of the time given a char* what you want to do is print the characters it points at.

I don't think you mean print the address of charptr (that would just be cout << &charptr), I think you mean print the address which is the value of charptr. The way to do that is to cast the address to void* before printing it.

cout << static_cast<void*>(charptr);

Your third question is essentially what I explained in the first paragraph above.

john
  • 85,011
  • 4
  • 57
  • 81