【问题标题】:Array creation int *array = new int[sizeof(int)*n]数组创建 int *array = new int[sizeof(int)*n]
【发布时间】:2020-07-19 05:00:57
【问题描述】:

你能解释一下这个语句发生了什么,特别是在括号内吗?

int *array = new int[sizeof(int) * n];

【问题讨论】:

    标签: c++ arrays pointers memory-management


    【解决方案1】:

    这是一个完整的 C++ 语句,sizeof 运算符的括号 () 包含 int 类型,sizeof(type) 给出了封闭类型的大小(以字节为单位):

    int *array = new int[ sizeof(int) * n ];
                                ^^^^^
    

    我相信您的意思是 new 表达式的方括号 [] 内的 表达式,即 sizeof(int) * n

    从语义上讲,表达式可能是错误的。

    如果您使用 new 运算符分配 10 个整数,则自动处理 sizeof(int)。您只需提供要分配的类型的元素数量。

    例如:

    int  n = 10;                // n can be an integer entered by the user
    int* a = new int[n];        // allocate an array of 10 integers
    

    在这种情况下,数组元素为default-initialized,并返回指向数组第一个元素的指针。

    而且,当你这样做时(假设你在一台 64 位机器上,即sizeof(int) 是 8):

    int  n = 10;
    int  s = sizeof(int) * n;   // 8 x 10 = 80
    int* a = new int[ s ];      // allocate an array of 80 integers
    

    这就是我之前所说的语义错误,因为其意图可能是分配 10 个整数,而不是 80 个。

    malloc() 需要表达式 sizeof(int) * n,您必须提供要分配的确切字节数,因此您需要提供该类型元素的确切数量。 malloc() 函数不会初始化分配的字节,它还会返回指向第一个元素的指针。

    例如:

    int  n = 10;
    int  s = sizeof(int) * n;
    int* a = (int*) malloc( s );
    

    你必须初始化malloc()分配的内存。有关这方面的更多信息,请参阅上述newmalloc() 的链接。


    除此之外,您正在分配内存,因此您有责任在完成后释放它。因此,理想情况下,newnew[] 将分别跟随 deletedelete[]。并且,malloc() 后面会跟着free()

    请参阅智能指针,例如std::unique_pointerstd::shared_ptr 以及 std::make_uniquestd::make_shared 用于基于 RAII 的自动内存管理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多