Question

C++ 1. What is the final output? 2. Why is 2 the ouput for (int)*c? Please...

C++

1. What is the final output?

2. Why is 2 the ouput for (int)*c? Please explain what happens during the line c = c + *p +1;

#include <iostream>
using namespace std;

int main() {
   int arr[5] = { 5,2,3,1,4 };

   int* p = arr;

   cout << (int)*p << endl;


   unsigned char* c = (unsigned char*)arr;


   p = p + 2;

   c = c + *p + 1;
  
   cout << (int)*p << endl;
   cout << (int)*c << endl;

   return 0;

}

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

Answer 1:

Output is 5,3,2

p is pointing to arr so when we access the P it will print the first element of the array

we are adding p+2 so now it will moves 2 blocks so points to 3rd element which 3 so it prints 3

so now are c is pointing to starting of the array , next we are adding c+*p+1 means c+3+1 so we are adding 4 to c it will move 4 blocks

In 2nd cout we are type casting to int * means now we are converting back to int address so adding 4 to int address means it will point to 2 block so it will print 2

Answer 2: there we are converting it to Int address to get the 2nd element from the array

Note : If you like my answer please rate and help me it is very Imp for me

Add a comment
Know the answer?
Add Answer to:
C++ 1. What is the final output? 2. Why is 2 the ouput for (int)*c? Please...
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