#include<iostream>intmain(){intarray[5]{9,7,5,3,1};// 打印数组的首地址std::cout<<"Element 0 has address: "<<&array[0]<<'\n';// 打印数组退化后的指针std::cout<<"The array decays to a pointer holding address: "<<array<<'\n';return0;}
在笔者的电脑上会打印如下内容:
12
Element 0 has address: 0042FD5C
The array decays to a pointer holding address: 0042FD5C
intarray[5]{9,7,5,3,1};// Deferencing an array returns the first element (element 0)std::cout<<*array;// will print 9!charname[]{"Jason"};// C-style string (also an array)std::cout<<*name<<'\n';// will print 'J'
#include<iostream>intmain(){intarray[5]{9,7,5,3,1};std::cout<<*array<<'\n';// will print 9int*ptr{array};std::cout<<*ptr<<'\n';// will print 9return0;}
数组退化为了int*类型的指针,而ptr也是此类型的指针。
指针和固定数组的差异
在一些情况下,固定数组和指针之间的类型差异会带来问题。这些问题有助于我们解释固定数组和指针的不同。
主要的差异发生在使用 sizeof() 操作符时。当用于固定数组时,sizeof返回整个数组的大小(array length * element size)。当用于指针时,sizeof 返回指针的大小(以字节为单位)。下面的程序说明了这一点:
1 2 3 4 5 6 7 8 910111213
#include<iostream>intmain(){intarray[5]{9,7,5,3,1};std::cout<<sizeof(array)<<'\n';// will print sizeof(int) * array lengthint*ptr{array};std::cout<<sizeof(ptr)<<'\n';// will print the size of a pointerreturn0;}
#include<iostream>voidprintSize(int*array){// array is treated as a pointer herestd::cout<<sizeof(array)<<'\n';// prints the size of a pointer, not the size of the array!}intmain(){intarray[]{1,1,2,3,5,8,13,21};std::cout<<sizeof(array)<<'\n';// will print sizeof(int) * array lengthprintSize(array);// the array argument decays into a pointer herereturn0;}
12
32
4
注意,即使形参声明为固定数组,也会发生这种情况:
1 2 3 4 5 6 7 8 9101112131415161718
#include<iostream>// C++ will implicitly convert parameter array[] to *arrayvoidprintSize(intarray[]){// array is treated as a pointer here, not a fixed arraystd::cout<<sizeof(array)<<'\n';// prints the size of a pointer, not the size of the array!}intmain(){intarray[]{1,1,2,3,5,8,13,21};std::cout<<sizeof(array)<<'\n';// will print sizeof(int) * array lengthprintSize(array);// the array argument decays into a pointer herereturn0;}
#include<iostream>// parameter ptr contains a copy of the array's addressvoidchangeArray(int*ptr){*ptr=5;// so changing an array element changes the _actual_ array}intmain(){intarray[]{1,1,2,3,5,8,13,21};std::cout<<"Element 0 has value: "<<array[0]<<'\n';changeArray(array);std::cout<<"Element 0 has value: "<<array[0]<<'\n';return0;}