2012-06-03 4 views
1

printf()이있는 char 포인터를 인쇄 할 때 주소를 인쇄할지 또는 % u 또는 % s에 따라 전체 문자열을 변환 지정자로 결정합니다.char 포인터가 Cout에서 cout과 혼동 됨

그러나 cout으로 동일한 작업을 수행하려는 경우 cout 주소와 전체 문자열 사이에 어떤 내용을 인쇄해야합니까?

다음
int main() 
{ 
    char ch='a'; 
    char *cptr=&ch; 
    cout<<cptr<<endl; 
    return 0; 
} 

, 내 GNU 컴파일러에, cout 문자열로 출력 채널에 노력하고있다 예를 들면 다음과 같습니다 소스입니다.

cout을 사용하여 cptr을 통해 ch의 주소를 얻는 방법은 무엇입니까?

+0

[cout <<와 char \ * 인수를 사용하면 가능한 포인터 값이 아닌 문자열을 출력 할 수 있습니다.] (http://stackoverflow.com/questions/17813423/cout-with-char-argument-prints-string-not-pointer - 가치) – GingerPlusPlus

답변

12

오버로드 해상도는 C 스타일 문자열 인쇄에 사용되는 ostream& operator<<(ostream& o, const char *c);을 선택합니다. 다른 ostream& operator<<(ostream& o, const void *p);을 선택하려고합니다. 당신은 여기 캐스트와 떨어져 아마 최고 :

cout << static_cast<void *>(cptr) << endl; 
+0

'static_cast '는이 경우 충분해야합니다. 기본 데이터 유형 포인터에 대한 이야기이기 때문입니다. – Zeta

+0

@ Zeta : 예. 편집 됨. – dirkgently

7

coutchar *을 수신하면 문자열을 출력합니다. 여기

ostream에 대한 operator <<에 대한 오버로드가 있습니다 : 당신이 주소를 원하는 경우

ostream& operator<< (bool val); 
ostream& operator<< (short val); 
ostream& operator<< (unsigned short val); 
ostream& operator<< (int val); 
ostream& operator<< (unsigned int val); 
ostream& operator<< (long val); 
ostream& operator<< (unsigned long val); 
ostream& operator<< (float val); 
ostream& operator<< (double val); 
ostream& operator<< (long double val); 
ostream& operator<< (const void* val); 

ostream& operator<< (streambuf* sb); 

ostream& operator<< (ostream& (*pf)(ostream&)); 
ostream& operator<< (ios& (*pf)(ios&)); 
ostream& operator<< (ios_base& (*pf)(ios_base&)); 

ostream& operator<< (ostream& out, char c); 
ostream& operator<< (ostream& out, signed char c); 
ostream& operator<< (ostream& out, unsigned char c); 


//this is called 
ostream& operator<< (ostream& out, const char* s); 
ostream& operator<< (ostream& out, const signed char* s); 
ostream& operator<< (ostream& out, const unsigned char* s); 

, 당신이 원하는 :

ostream& operator<< (const void* val); 

그래서 당신은 const void*으로 캐스팅해야합니다.

+0

그런 세부 사항에 감사드립니다 ... :) 그것은 매우 도움이 .. –

4

그것은 C 문자열로 해석하려고하지 않습니다 그래서 난 그냥 * 무효로 캐스팅 것 :

cout << (void*) cptr << endl; 

그러나, 안전한 옵션 dirkgently의 대답으로 static_cast 사용하는 것입니다 (캐스팅은 적어도 컴파일 타임에 확인됩니다.

+1

C 스타일의 캐스트? C++ 캐스트를 사용하는 것이 더 안전하지 않습니까? –

+0

@AdrienPlisson reinterpret_cast 이외의 C++ 캐스트보다 덜 안전합니다. 이처럼 사소한 경우에는 C++ 스타일의 캐스트로 신경 쓰지 않을 것입니다. 일단 코드베이스가 충분히 커지면 정말로 이상한 주조가 일어날 수 있다고 확신 할지라도, 그 코드를 무효화하는 캐스트가 해롭다는 것을 예측하는 것은 어렵습니다. – Corbin

+0

@Corbin :'void *'의 경우, C++ 11의'reinterpret_cast'는 괜찮습니다. [Issue # 1120] (http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1120)을 참조하십시오. – dirkgently

0

Luchian 말했듯이, cout을가 종류에 따라 인쇄하는 것을 알고있다. 포인터 값을 인쇄하려면 void *로 포인터를 캐스팅해야 포인터로 삽입됩니다.