简体   繁体   English

C ++创建和初始化数组的最佳方法

[英]c++ the best way of creating and initializing array

What is better(more efficient) way of creating and initializing array ? 什么是更好(更有效)的创建和初始化数组的方法?

1. int array[3] {1,2,3};

2. int *array=new int[3]{1,2,3};

Don't assume that "better" always means more efficient! 不要以为“更好”总是意味着更有效率! In a function body, these two do very different things: 在功能体内,这两个功能有很大不同:

int array[3] {1,2,3};

The first allocates local storage (on the stack) which will be released when the function terminates. 第一个分配本地存储(在堆栈上),该存储将在函数终止时释放。 (so you should not attempt to use it beyond that lifetime). (因此,您不应该尝试在此期限内使用它)。

int *array = new int[3] {1,2,3};

The second allocates new heap memory, which will not be released when the function terminates. 第二个分配新的堆内存,函数终止时不会释放该堆内存。 (so you should remember to delete[] it when it is no longer required) (因此,当不再需要它时,请记住将其delete[]

The best way is: 最好的方法是:

 int array[3] = {1,2,3}; // assignment operator added

In your examples only the 1st is array: 在您的示例中,第一个是数组:

 int array[3];

The second one is a pointer that assigned with address returned by operator new . 第二个是分配了由new运算符返回的地址的指针。 To see the difference try sizeof(array) for both: 要查看两者的区别,请尝试使用sizeof(array)两者:

int array[3];
cout << sizeof(array) << endl;

with my compiler shows 12 (ie 3 * sizeof(int), size of array depends on number of elements ), but 与我的编译器显示12(即3 * sizeof(int),数组的大小取决于元素数),但是

int *array=new int[3];
cout << sizeof(array) << end

for my compiler shows 4 (ie sizeof(int*), size of pointer depends only from platform) 对于我的编译器显示4(即sizeof(int *),指针的大小仅取决于平台)

lets start with second one. 让我们从第二个开始。 int *array = new int[3] {1,2,3} ; int *array = new int[3] {1,2,3} ;

It creates a dynamic array.'Dynamic' means that the memory will be allocated during the run-time and not while compiling.So your above initialization will create an array of size 3 and it will be initialized with the given values. 它创建一个动态数组.``动态''意味着将在运行时而不是在编译时分配内存,因此您上面的初始化将创建一个大小为3的数组,并使用给定的值进行初始化。 Remember dynamic allocated memory has no predefined scope ,hence the memory needs to be released using 'delete' operator. 请记住,动态分配的内存没有预定义的范围,因此需要使用“删除”运算符来释放内存。 Also be careful while using pointers ,as they may create havoc in your program if not used properly! 使用指针时也要小心,因为如果使用不正确,它们可能会对您的程序造成破坏!

Now the first one. 现在是第一个。 int array[3] = {1,2,3};

It creates an array of size 3 and initializes it with the given values. 它创建一个大小为3的数组,并使用给定的值对其进行初始化。 And in this the memory is allocated statically(during compilation). 并且在这种情况下,内存是静态分配的(在编译过程中)。 As long as the program continues the variable stays in memory and then vanish! 只要程序继续运行,变量就会保留在内存中,然后消失! So you can decide the type of array initialization as per your requirement. 因此,您可以根据需要确定数组初始化的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM