|
From: Ioannis V. <no...@ya...> - 2001-12-29 13:32:01
|
I saw that i made a mistake, so i resend.
> -----Original Message-----
> From: dev...@li...
> [mailto:dev...@li...] On Behalf
> Of Green, Aaron
> Sent: Saturday, December 29, 2001 3:19 AM
> To: dev-c++ user's mailing list
> Subject: [Dev-C++] C++ pointers
>
>
> This may be OT, but I know I've seen programming questions
> here before, so I'll give it a try.
>
> I wrote up a small program that tries to explain how pointers
> work to me.
>
> #include <iostream>
>
> double* f(double *pD2)
> {
> *pD2 = 15;
> return pD2;
> }
>
> int main()
> {
> double d;
> double *pD = &d;
> d = 20;
> *pD = 10;
> std::cout << *pD << '\n';
> std::cout << d << '\n';
> double *pD3 = f(&d);
This points pD3 toy d which after the execution of this line is 15.
> std::cout << d << '\n';
> std::cout << *pD3 << '\n';
> d = 100;
Now you change d toy 100 so *pD3 is now 100 (pD3==&d).
> std::cout << d << '\n';
> std::cout << *pD3 << '\n';
> std::cout << *pD << '\n';
>
>
> return 0;
> }
>
>
> The last parts of the output are 100 100 100. My
> question is: Why does *pD3 change when it points to a
> function that changes whatever is at &d ? I thought calling
> cout would run that function again, or at least give me the
> same value as before.
Calling cout<<*pD3; doesn't execute any function it simply the value of
d which is 100. If you wanted the function to be called again you should
do:
std::cout << *(pD3=f(pD3)) << '\n';
(or std::cout << *(pD3=f(&d)) << '\n'; )
or std::cout << *f(pD3) << '\n'
( or std::cout << *f(&d) << '\n' )
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.f2s.com
* Alternative URL: http://run.to/noicys
|