C++动态分配指针和数组

测试环境编译器:
g++.png
  1. 使用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
  1. 数组指针
    数组名指向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个字节。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容