计算机是把数组以一组连续的内存块保存的。
数组的第一个元素的地址为该数组的基地址。
实例1:数组元素地址打印
1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 { 7 const unsigned short ITEMS = 5; 8 int intArray[ITEMS] = {1,2,3,4,5}; 9 char charArray[ITEMS] = {'F','i','s','h','C'}; 10 11 int *intPtr = intArray; 12 char *charPtr = charArray; 13 14 cout << "整型数组输出:" << '\n'; 15 for(int i=0;i < ITEMS; i++) 16 { 17 std::cout << *intPtr << " at " << (intPtr) << '\n';//用reinterpret_cast把指针类型强制转换为unsigned int 18 intPtr++;//地址加上以其所定义的类型所占的字节 19 } 20 21 cout << "字符型数组输出:" << '\n'; 22 for(int i=0;i < ITEMS; i++) 23 { 24 cout << *charPtr << " at " << (charPtr) << '\n'; 25 charPtr++; 26 } 27 return 0; 28 }
实例2:数组重载
1 #include <iostream> 2 3 using namespace std; 4 5 void print(int *pBegin,int *pEnd) 6 { 7 while(pBegin != pEnd) 8 { 9 cout << *pBegin; 10 ++pBegin;//地址加1 11 } 12 } 13 14 void print(char *pBegin,char *pEnd) 15 { 16 while(pBegin != pEnd) 17 { 18 cout << *pBegin; 19 ++pBegin;//地址加1 20 } 21 } 22 int main() 23 { 24 int num[5] = {0,1,2,3,4}; 25 char name[5] = {'F','i','s','h','C'}; 26 27 print(num,num + 5); 28 cout << '\n'; 29 print(name,name + 5); 30 cout << '\n'; 31 32 return 0; 33 }
实例3:泛型数组重载
1 #include <iostream> 2 3 using namespace std; 4 5 template <typename elemType>//将输入参数typename的类型赋值给elemType 6 void print(elemType *pBegin,elemType *pEnd) 7 { 8 while(pBegin != pEnd) 9 { 10 cout << *pBegin; 11 ++pBegin;//地址加1 12 } 13 } 14 15 int main() 16 { 17 int num[5] = {0,1,2,3,4}; 18 char name[5] = {'F','i','s','h','C'}; 19 20 print(num,num + 5); 21 cout << '\n'; 22 print(name,name + 5); 23 cout << '\n'; 24 25 return 0; 26 }标签:cout,int,elemType,数据类型,C++,pBegin,pEnd,数组,指针 From: https://www.cnblogs.com/ybqjymy/p/17640362.html