11.4k views
0 votes
What will be the output of the code: int *numbers = new int[5]; for (int i = 0; i <= 4; i++) *(numbers + i) = i; cout << numbers[2] << endl;?

A) 0
B) 1
C) 2
D) 3

User Hemanto
by
7.9k points

1 Answer

4 votes

Final answer:

The output of the code will be 2.

Step-by-step explanation:

The output of the code will be 2. The code first dynamically allocates an array of integers called numbers with a size of 5 using the new operator. Then, it uses a for loop to assign values to each element of the array.

The expression *(numbers + i) is used to access the elements of the array. Here, the position of the element is calculated by adding the value of i to the base address of the array, and then, the value at that memory location is assigned to i. Therefore, the element at index 2 (third element) of the numbers array will be assigned the value 2.

Finally, the value of numbers[2] is printed, which will be 2.

User Petri Tuononen
by
7.9k points