0

Someone explain step by step

#include <iostream> using namespace std; int main() { int a[4] = {0, 1, 2, 3}; a[1] = *(a+2); *(a+2) = a[3]++; cout << a[1] + a[2]; return 0; } // Outputs 5 Someone please explain this code step by step. You can copy paste the code in your answer and after each line of code you can use // to comment each line step by step, no need for "return 0" tho 😊 Thanks.

28th Nov 2016, 10:16 PM
Mielu
Mielu - avatar
4 odpowiedzi
+ 5
int a[4] = {0, 1, 2, 3}; //declare an array which can hold 4 int members and assigning the values. array index starts from 0. a[0]=0,a[1]=1,a[2]=2,a[3]=3. a[1] = *(a+2); //evaluates to a[1]=a[2]. for *(a+2) a passes base address of array i.e. a[0] and you increment the base address by 2 units. so you reach at a[2]. So a[1]=2 *(a+2) = a[3]++; //Similarly the value at[2] gets three and value of a[3] gets incremented to 4 after that. cout << a[1] + a[2]; //2+3=5 your output. return 0;
28th Nov 2016, 11:42 PM
Megatron
Megatron - avatar
+ 1
so basically *(a+2) is in fact a [2] ?
29th Nov 2016, 3:46 AM
Mielu
Mielu - avatar
+ 1
yes/no well you can say that but compiler doesn't interprets *(a+2) as a[2] but does reverse. Also this is the reason that index starts from 0 in any programming language. if 'a' is the base address then you must add nothing to it to get to the first number of array. so a[0] is the first element. and add 1 to get next address 2 to get next and so on.....
29th Nov 2016, 4:09 AM
Megatron
Megatron - avatar
0
I know how arrays / vectors works and I know about the "index" and everything... What confuses me is that asterisk " * " before that (a+2), that's basically what put me on fire and that's why I was unable to understand wth is that asterisk doing there... Is it a pointer? is it something else? wth does it do... these were the questions that raised in my head 😠 and couldn't find an answer 😟
29th Nov 2016, 7:09 AM
Mielu
Mielu - avatar