Question

What does this print to the screen? #include <iostream> using namespace std; int main () {...

What does this print to the screen?

#include <iostream>

using namespace std;

int main ()

{

int *a;

a = new int[2];

for(int i = 0; i < 2; i++)

*(a + i) = i;

for(int i = 0; i < 2; i++)

cout << a[i] << " ";

delete [] a;

return 0;

}

I'm getting 0 1

Please step me through the process.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

First of all we declare a pointer a. Now we allocate it memory equal to an array size of 2.

This means that we can now store integers at (a + 0) and (a + 1) locations.

Now in the first for loop, we initialise this new memory in the following way:-

*(a + i) = i for i = 0, 1

This means that store value of i at the memory location (a + i).

Thus, now (a + 0) points to an integer value 0 and (a + 1) points to an integer value 1.

Now *(a + i) , i.e., value at position (a + i) can also be written as a[i]. Thus the next for loop prints value at a and a + 1 locations.

Thus, a[0] = *(a + 0) = 0 and a[1] = *(a + 1) = 1

Thus the output is:-

0 1

Add a comment
Know the answer?
Add Answer to:
What does this print to the screen? #include <iostream> using namespace std; int main () {...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT