0

What's the difference between the two code below.

int a[] = {0,0};
int a[2] = {0,0};

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?

2
  • 2
    You can't access a[3] in either case, regardless of what your compiler lets you do. This has been asked before. Commented Mar 15, 2010 at 3:34
  • There is no spoon^H^H^H^H^H a[3]. (Hey, why doesn't strike work in comments?) Commented Mar 15, 2010 at 3:56

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

IOW, doesn't mean you can do something that you should.
2

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

Comments

2

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...

2 Comments

I doubt a[3] will cause a segfault, but it depends on where a is and "how far" out of bounds a[3] is and how sensitive your system is.
true that Chris. I just like to assume or scare develops into assuming that writting out side of the array bounds is the root of all evil
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.