Reputation: 19
1. int *a;
2. a=new int[2];
3. cin>>a[0];
4. cout<<a<<"\n";
5. cout<<&a<<"\n";
6. cout<<*a;
What will be the output of 5th line? I know that 4th line will give the address of first element of array a and 6th line will give the value of the first element of array a. But I cannot figure out whose address is given by 5th line.
Thanks.
edit: This is the output after compiling.
4 is taken as input. 0x5d2158 is the output of 4th line 0x28fefc is the output of 5th line 4 is the output of 6th line
Upvotes: 0
Views: 115
Reputation: 1293
It will give address of pointer 'a' it self. explain in diagram. Address of a is '0x7fffa28413c8' hence output of &a is 0x7fffa28413c8. https://i.sstatic.net/iPobm.png
Upvotes: 0
Reputation: 24344
Explanation of each line of your input:
int *a;
declares a pointer to an inta=new int[2];
allocates array of ints of size two and assigns the address of the first element(index 0) to pointer a
cin>>a[0];
reads value from standard input and assigns it to first (index 0) element of array a
cout<<a<<"\n";
prints address of where a
points to, meaning address of first element(index 0) of your array of ints of size 2cout<<&a<<"\n";
prints address at which pointer a
is stored (i.e. location of the pointer in the memory) cout<<*a;
prints the value a
points at, meaning first element of a
arrayUpvotes: 1
Reputation: 4656
It will give the address of the pointer a
itself. Pointers also take space in the memory to store the address of actual data they are pointing to, in this case which is an integer array.
Upvotes: 1