0

When i try to assign values to an array like this:

int ar[5] = {18,19,20,21,22,23};

I get a compiler error: too many initializers for 'int [5]'

But when I do it like this:

int ar[5];
ar[0] = 12, ar[1] = 13, ar[2] = 14, ar[3] = 15, ar[4] = 16, ar[5] = 17;

Everthing is fine and the program runs fine and outputs correct results, am I doing something wrong or?

1
  • int ar[5] means array of size 5. The indices will be from 0 to 4 only. {18,19,20,21,22,23} contains 6 numbers, and compiler was expecting 5 numbers. in case of ar[5] = 17, since cpp doesn't check for limits/size of array, it just puts 17 at the calculated memory address... Commented May 17, 2020 at 17:31

2 Answers 2

4

Yes, you are doing something wrong here:

ar[5] = 17;

by invoking undefined behavior. You can't index the 6th element (which is stored at the index 5) of an array containing only 5 elements.

The fact that the program runs and gives the correct output is an accident. You can't rely on this, and the program is fundamentally broken.

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

Comments

0

Int[5] can only hold 5 elements but you are giving it 6. Hence error. use ar[6] or remove an element from the array.

Second case is undefined behavior, the compiler just calculates and places the value without checking if it belongs to the array, and may likely overwrite any other variable data.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.