avneetmalhotra
avneetmalhotra

Reputation: 19

What will be the output?

 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

Answers (4)

User2
User2

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

syntagma
syntagma

Reputation: 24344

Explanation of each line of your input:

  1. int *a; declares a pointer to an int
  2. a=new int[2]; allocates array of ints of size two and assigns the address of the first element(index 0) to pointer a
  3. cin>>a[0]; reads value from standard input and assigns it to first (index 0) element of array a
  4. cout<<a<<"\n"; prints address of where a points to, meaning address of first element(index 0) of your array of ints of size 2
  5. cout<<&a<<"\n"; prints address at which pointer a is stored (i.e. location of the pointer in the memory)
  6. cout<<*a; prints the value a points at, meaning first element of a array

Upvotes: 1

Asif Mujteba
Asif Mujteba

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

Pawan
Pawan

Reputation: 167

It will give address of first element. That's it

Upvotes: 0

Related Questions