Home > Enterprise >  How the 11th element got added into array if the decalred array is arr[10]?
How the 11th element got added into array if the decalred array is arr[10]?

Time:01-05

The code

using namespace std;
int main ()
{
    int arr[10], n, i, sum = 0, pro = 1;
    cout << "Enter the size of the array : ";
    cin >> n;
    cout << "\nEnter the elements of the array : ";
    for (i = 0; i < n; i  )
    cin >> arr[i];
    for (i = 0; i < n; i  )
    {
        sum  = arr[i];
        pro *= arr[i];
    }
    cout << "\nSum of array elements : " << sum;
    cout << "\nProduct of array elements : " << pro;
    return 0;
}

Here, I did not understand how the 11 can be given as input to get the sum and the product

Output sample

Enter the size of the array : 11

Enter the elements of the array : 11 10 9 8 7 6 5 4 3 2 1

Sum of array elements : 66

Product of array elements : 39916800

CodePudding user response:

The positions of an array start at 0, so if you start counting from 0, the element in position 10 is on 11

CodePudding user response:

That's because arrays are actually pointers.

When you create an array, you are basically telling the compiler to reserve enough space to store all elements of the array. When you access the 11th element of the array you are accessing part of the memory that is not reserved for your array, which I think is considered undefined behaviour.

Try the following:

int a = 24;
int b = 24;
int c = 24;
int d = 24;
int arr[0];
int e = 24;
int f = 24;
int g = 24;
int h = 24;

cout << arr[2];

You will probably see the number 24 printed to the screen because you are accessing some memory that is reserved for other variables.

  •  Tags:  
  • Related