- 使用new对指针进行动态分配空间
可以看到指针的地址和内存所在地址不相同(指针存储在自动分配区域,指针指向空间存储在动态空间)
对指针和动态数组首个元素进行+1操作。
指针是大小为8字节,对自身加一自然会对地址增加自身大小;
动态数组首个元素指针结果为2,原因是short类型为2字节
#include <iostream>
int main()
{
short *tell = new short[5];
tell[0] = 1; tell[1] = 2; tell[2] = 3; tell [3] = 4; tell[4] = 5;
std::cout << "short *tell = new short[5]\n";
std::cout << "&tell = " << &tell << std::endl;
std::cout << "&tell + 1 = " << &tell + 1 << std::endl;
std::cout << "sizeof(&tell) = " << sizeof(&tell) << std::endl;
std::cout << "&tell[0] = " << &tell[0] << std::endl;
std::cout << "tell = " << tell << std::endl;
std::cout << "tell + 1 = " << tell + 1 << std::endl;
std::cout << "sizeof(tell) = " << sizeof(tell) << std::endl;
std::cout << "*tell = " << *tell << std::endl;
std::cout << "*(tell + 1) = " << *(tell + 1) << std::endl;
delete [] tell;
}
//运行结果:
short *tell = new short[5]
&tell = 0x7ffd499400f0
&tell + 1 = 0x7ffd499400f8
sizeof(&tell) = 8
&tell[0] = 0x1d43c20
tell = 0x1d43c20
tell + 1 = 0x1d43c22
sizeof(tell) = 8
*tell = 1
*(tell + 1) = 2
- 数组指针
数组名指向main函数栈内存中的第一个元素
对数组名+1操作和数组指针+1操作结果不同
数组名为首元素地址,对其+1则增加一个short的字节;
对数组地址+1则增加数组长度即5个short的长度,10
#include <iostream>
int main()
{
short tell[5];
tell[0] = 1; tell[1] = 2; tell[2] = 3; tell [3] = 4; tell[4] = 5;
std::cout << "short tell[5]\n";
std::cout << "&tell = " << &tell << std::endl;
std::cout << "&tell + 1 = " << &tell + 1 << std::endl;
std::cout << "sizeof(&tell) = " << sizeof(&tell) << std::endl;
std::cout << "&tell[0] = " << &tell[0] << std::endl;
std::cout << "tell = " << tell << std::endl;
std::cout << "tell + 1 = " << tell + 1 << std::endl;
std::cout << "sizeof(tell) = " << sizeof(tell) << std::endl;
std::cout << "*tell = " << *tell << std::endl;
std::cout << "*(tell + 1) = " << *(tell + 1) << std::endl;
}
//结果
short tell[5]
&tell = 0x7ffffd379e20
&tell + 1 = 0x7ffffd379e2a
sizeof(&tell) = 8
&tell[0] = 0x7ffffd379e20
tell = 0x7ffffd379e20
tell + 1 = 0x7ffffd379e22
sizeof(tell) = 10
*tell = 1
*(tell + 1) = 2
综上可以看出,数组和动态分配的指针大小不同。动态分配的数组指针大小为普通short指针大小8字节,而数组指针大小为数组大小5*2=10个字节。