开发者

One question with array declaration in C++

What's the difference between the two code below.

int a[] = {0,0};
int a[2] = {0,0}开发者_Python百科;

It seems I can assign value to a[3] in both cases. I can access a[3] in any case. So what's the difference?


There is no difference. In the first one, the compiler does the counting for you, which is nice if you decide to change the number of elements later on.

The fact that your compiler forgives you for assigning to or using a[3] doesn't mean that doing so is correct. In fact, you can't even access a[2] since it only has two elements, indexed by subscripts 0 and 1.


a[3] is equally undefined in both instances. Don't do it.


You can access a[100000000] if you wanted to, but it doesnt mean its going to be in your array.

You have declared an array of length two in either case. Writing to a[3] is most likely going to cause a segmentation fault.

The highest element you can access is a[ARRAY_SIZE-1], so that makes it a[1].

Both those lines of code do the same thing...


C++ in general does NOT do bounds checking on arrays - sorry ;) So, you can even access a[200] - you jus would access SOMETHING outside your array.

In the first line, you create an array of two elements, in the second line I acutally think it is an array of three elements, with the values 0, 0, undefined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜