初始化数组时使用(或不使用)括号 [英] Using (or not using) parentheses when initializing an array

查看:112
本文介绍了初始化数组时使用(或不使用)括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在阅读的c ++代码中,有一些初始化为的数组

In the c++ code that I am reading through there are some arrays initialised like

int *foo = new int[length];

和一些类似的

int *foo = new int[length]();

我的快速实验无法检测到这两者之间的任何区别,但是它们彼此相邻使用.

My quick experimentation could not detect any difference between these two, yet they are used right next to one another.

有区别吗?

编辑;因为有人断言第一个应该给出不确定的输出,所以这里的测试表明可疑的数字为0;

Edit; since there is an assertion that the first one should give indeterminate output here is a test showing a suspicious number of 0s;

[s1208067@hobgoblin testCode]$ cat arrayTest.cc
//Test how array initilization works
#include <iostream>
using namespace std;
int main(){
int length = 30;
//Without parenthsis
int * bar = new int[length];
for(int i=0; i<length; i++) cout << bar[0] << " ";

cout << endl;
//With parenthsis 
int * foo = new int[length]();
for(int i=0; i<length; i++) cout << foo[0] << " ";


cout << endl;
return 0;
}
[s1208067@hobgoblin testCode]$ g++ arrayTest.cc
[s1208067@hobgoblin testCode]$ ./a.out
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
[s1208067@hobgoblin testCode]$ 

编辑2;显然,该测试存在缺陷,请不要相信它-查看答案以获取详细信息

Edit 2; apparently this test was flawed, dont trust it - look at the answers for details

推荐答案

使用括号可确保将数组的所有元素初始化为0.我只是尝试使用以下代码:

Using the parentheses guarantees that all elements of the array are initialized to 0. I just tried using the following code:

#include <iostream>
using namespace std;

int main(int,char*[]){
    int* foo = new int[8];
    cout << foo << endl;
    for(int i = 0; i < 8; i++)
        foo[i] = i;
    delete[] foo;
    foo = new int[8];
    cout << foo << endl;
    for(int i = 0; i < 8; i++)
        cout << foo[i] << '\t';
    cout << endl;
    delete[] foo;
    foo = new int[8]();
    cout << foo << endl;
    for(int i = 0; i < 8; i++)
        cout << foo[i] << '\t';
    cout << endl;
    delete[] foo;
    return 0;
}

当我编译并运行它时,看起来foo每次都分配在相同的内存位置中(尽管您可能不能依靠它).对我来说,上述程序的完整输出是:

When I compile and run this, it looks like foo is allocated in the same memory location each time (though you probably can't rely on this). The full output of the above program for me is:

0x101300900
0x101300900
0   1   2   3   4   5   6   7   
0x101300900
0   0   0   0   0   0   0   0

因此,您可以看到foo的第二个分配不会触及分配的内存,而使其处于与第一次分配相同的状态.

So, you can see that the second allocation of foo doesn't touch the memory allocated, leaving it in the same state that it was left in from the first allocation.

这篇关于初始化数组时使用(或不使用)括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆