Click here to Skip to main content
15,891,409 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include <iostream>
using namespace std;
int main()
{
 int* a = new int[10];
 for(int i = 0; i<10; i++)
 a[i] = i;
 int* b = &a[2];
 cout << b[3];
}

Output: 5


What I have tried:

I don't understand why the output is 5.
Posted
Updated 14-Oct-18 21:13pm
v2

1 solution

The reason for that output is something called pointer arithmetic. Arrays are stored sequentially in memory. So the offset from one value to the next is the size of the type. Integer = 4 bytes, float = 4 bytes, double = 8 bytes, etc. This is the fundamental reason why pointer arithmetic works. When you say a[2], what you're really saying is "the pointer to the start of the array (i.e. the first element) plus two offsets worth of integers to reach the third value." You can test this by doing "*(a+2)" which will yield the same result as a[2].

So what's happening in the code you posted: the address (&) of a[2] is being assigned to b. Then you're printing to the standard output stream the value of 3 offsets worth of integers (b[3]). This is 5.

b[0] = a[2]
b[1] = a[3]
b[2] = a[4]
b[3] = a[5]
 
Share this answer
 
Comments
CPallini 15-Oct-18 3:13am    
5.
codingBlonde 15-Oct-18 10:57am    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900