在C++中,如果cout一個(gè)字符數(shù)組的話,那么它會沿著這個(gè)地址,一直輸出這個(gè)字符串,直到遇到'/0'實(shí)際上,C++標(biāo)準(zhǔn)庫中I/O類對輸出操作符<<重載,在遇到字符型指針時(shí)會將其當(dāng)做字符串名來處理,輸出指針?biāo)傅淖址<热贿@樣,我們就別讓他知道那是字符型指針,所以得進(jìn)行類型轉(zhuǎn)換,即:希望任何字符型的指針變量輸出為地址的話,都要作一個(gè)轉(zhuǎn)換,即強(qiáng)制char *轉(zhuǎn)換成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<<"整形數(shù)組輸出"<<"/n";for(int i=0;i<ITEMS;i++){std::cout<<*intPointer<<" at "<<intPointer<<"/n" ;intPointer++;}std::cout<<"字符型數(shù)組輸出"<<"/n";for(int i=0;i<ITEMS;i++){std::cout<<*charPointer<<" at "<<charPointer<<"/n" ;charPointer++;}return 0;}
整形數(shù)組輸出1 at 0x29ff002 at 0x29ff043 at 0x29ff084 at 0x29ff0c5 at 0x29ff10字符型數(shù)組輸出L at LMYLR@M at MYLR@Y at YLR@L at LR@R at R@
對字符型指針進(jìn)行強(qiáng)制類型轉(zhuǎn)換之后:
#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<<"整形數(shù)組輸出"<<"/n";for(int i=0;i<ITEMS;i++){std::cout<<*intPointer<<" at "<<intPointer<<"/n" ;intPointer++;}std::cout<<"字符型數(shù)組輸出"<<"/n";for(int i=0;i<ITEMS;i++){std::cout<<*charPointer<<" at "<<(void *)charPointer<<"/n" ;charPointer++;}return 0;}
整形數(shù)組輸出1 at 0x29ff002 at 0x29ff043 at 0x29ff084 at 0x29ff0c5 at 0x29ff10字符型數(shù)組輸出L at 0x29fef0M at 0x29fef1Y at 0x29fef2L at 0x29fef3R at 0x29fef4
新聞熱點(diǎn)
疑難解答
圖片精選