在C++中,如果cout一個字符數組的話,那么它會沿著這個地址,一直輸出這個字符串,直到遇到'/0'實際上,C++標準庫中I/O類對輸出操作符<<重載,在遇到字符型指針時會將其當做字符串名來處理,輸出指針所指的字符串。既然這樣,我們就別讓他知道那是字符型指針,所以得進行類型轉換,即:希望任何字符型的指針變量輸出為地址的話,都要作一個轉換,即強制char *轉換成void *
#include<iostream>int main(){const short ITEMS=5;int intArray[ITEMS]={1,2,3,4,5};char charArray[ITEMS]={'L','M','Y','L','R'};int *intPointer=intArray;char *charPointer=charArray;std::cout<<"整形數組輸出"<<"/n";for(int i=0;i<ITEMS;i++){std::cout<<*intPointer<<" at "<<intPointer<<"/n" ;intPointer++;}std::cout<<"字符型數組輸出"<<"/n";for(int i=0;i<ITEMS;i++){std::cout<<*charPointer<<" at "<<charPointer<<"/n" ;charPointer++;}return 0;}
整形數組輸出1 at 0x29ff002 at 0x29ff043 at 0x29ff084 at 0x29ff0c5 at 0x29ff10字符型數組輸出L at LMYLR@M at MYLR@Y at YLR@L at LR@R at R@
對字符型指針進行強制類型轉換之后:
#include<iostream>int main(){const short ITEMS=5;int intArray[ITEMS]={1,2,3,4,5};char charArray[ITEMS]={'L','M','Y','L','R'};int *intPointer=intArray;char *charPointer=charArray;std::cout<<"整形數組輸出"<<"/n";for(int i=0;i<ITEMS;i++){std::cout<<*intPointer<<" at "<<intPointer<<"/n" ;intPointer++;}std::cout<<"字符型數組輸出"<<"/n";for(int i=0;i<ITEMS;i++){std::cout<<*charPointer<<" at "<<(void *)charPointer<<"/n" ;charPointer++;}return 0;}
整形數組輸出1 at 0x29ff002 at 0x29ff043 at 0x29ff084 at 0x29ff0c5 at 0x29ff10字符型數組輸出L at 0x29fef0M at 0x29fef1Y at 0x29fef2L at 0x29fef3R at 0x29fef4
新聞熱點
疑難解答
圖片精選