0
#include <iostream> using namespace std; int main() { int x=10,y=20; int *ptr = &x; int &ref= y; *ptr++; ref++; cout<<x<<y
please explain the code and its output in detail..
9 odpowiedzi
+ 1
https://code.sololearn.com/cCDCJ5MCdCTe/?ref=app
If you want more informations ask !
0
Do you know and UNDERSTAND pointers ? 😇
0
Yes but i couldn't understand this code
0
Do you know parameters by reference (int &) ?
Look at this piece of code :
void function(int &a, &b){}
int main(){
int c, d;
function (c, d);
}
When 'function(c, d)' is executed, that's like :
int &a=c, &b=d
and then, every changes on 'function' apply on 'a' or 'b' is also apply on 'c' and 'd'.
If you still don't understand ask !
I'm going to post à code to explain.
0
The output of your code is 1021. Why not 1121??
0
Because the priority is to the increment:
*ptr++; // == *(ptr++);
So it's the value if the POINTER wich is incremented, not the value of 'x'.
But if you write this :
(*ptr)++; // The value of 'x'is incremented.
If you want more informations ask
0
I've modified the code take a look
0
#include <iostream>
using namespace std;
void function(int &ref){
ref++;
}
int main() {
int x=10,y=20;
int *ptr=&x;
(*ptr)++;
function(y);
cout << x << y << endl;
cout << *ptr << " " << ptr << endl;
*ptr++;
cout << x << " " << ptr;
return 0;
}
I have changed *ptr to x (2nd last line) which also changes the output. But these both mean the same thing. Don't they?
0
Well.. you've understood.
However, when '*ptr++;' is written, remember it is like '*(ptr++);' so, in this case like 'ptr++;'.
ptr++; increments ptr's value wich is an ADRESS (x's address). Once this value incremented, it is ANOTHER ADRESS. So ptr points on another variable in the memory.
And *ptr != x anymore because ptr != &x