C++裏字符變量的地址顯示錯誤,通過網上搜索找到了原因

C++ 代碼如下所示:

// Program example P9EX1
// Program to display the address of variables.  
#include <iostream>
#include <iomanip>
#include  <string>
using namespace std ;

// Use templates here. T is called the type parameter, 
//T is normally used, but any valid name can be used.
template <typename T>
int display(string vtan,T *pvar)
  {
  	int k;
  	cout << vtan <<" is stored at  " << pvar << "	" ;
  	for (k = 0 ; k < sizeof (*pvar) ; k++)
    	    cout << "*"  ;
  	cout << endl ; 
	return 0;    
	}  

int main()
{
  
  string stan[5] = { "char c" , "int i" , "short s" , 
	"float f" , "double d" } ;
  char c = 'a' ;
  int i = 54321 ;
  short s = 123 ;
  float f = 125.5 ;
  double d = 1234.25 ;
  display (stan[0], &c);
  display (stan[1], &i);
  display (stan[2], &s);
  display (stan[3], &f);
  display (stan[4], &d);
  return 0;
}

後來在網上找到了一篇解決這個問題的博文。這個問題的具體原因和解決方法請看附錄。要想顯示字符變量的地址,解決辦法是強制轉換 &c 類型。我將一行代碼:

display (stan[0],  &c); 

修改成:

cout << "char c is stored at: " << (int *) &c <<"   *" <<  endl;

修改以後編譯運行該程序,輸出如下所示:

char c is stored at: 0x6ffdea   *
int i is stored at  0x6ffdcc    ****
short s is stored at  0x6ffdca  **
float f is stored at  0x6ffdc4  ****
double d is stored at  0x6ffdb8 ********

 

就這樣解決了這個問題。

參考博文講了這種情況的原因。爲了內容的完整性,下面附有參考博文的部分內容。

---------------------------------------------------------------------------------------------------------------------------------

附錄

c++通過cout輸出字符變量的地址

今天,我遇到了這樣的一種情況,我想輸出一個字符串的首地址。
那麼該怎麼輸出呢?通常我們可能的想法是直接cout啊。
比如:

char ss[20]="hello";
cout<<ss<<endl;

運行結果:
hello

……

通過上面的例子我們會發現,只要我們cout後面的輸出對象是一個char*的類型時,它都會當作要輸出這個地址指向的字符串來執行。它會從這個地址開始輸出字符,直到遇到’\0’停止。那我們怎樣才能讓cout輸出char*類型存值的地址呢?
c是靠%s,%x,%p來區分指針表達式&ss[0]的輸出形式的;c++沒有這個格式控制,只能按一種形式輸出。
c++標準庫中I/O類對輸出操作符<<重載,在遇到字符型指針時會將其當做字符串名來處理,輸出指針所指的字符串。
既然是這樣,我們只需要將char*類型的指針進行強制轉換成別的類型的指針,cout就會輸出指針存儲的地址。我們可以把它強轉成void*類型。
————————————————
版權聲明:本文爲CSDN博主「Rotation.」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/fengxinlinux/article/details/75768613

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章