Re: [Dev-C++] whats wrong with this?
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Jonathan W. <jon...@gm...> - 2007-05-21 09:14:06
|
Hi,
You are missing a level of indirection:
the 'a' you are setting here (a=temp) is a local variable in the function
'call', so you can access the int that it points to, but not the pointer
that main knows
The a that main knows is always an uninitialized pointer, and you're just
lucky it's not segfaulting :D
to change the pointer main knows, you need a pointer or a reference to that
pointer. ie.:
(by pointer)
bool call(int **a) {
static int x;
++x;
int *temp=new int;
*temp=x;
*a=temp;
cout<<"call->"<<x<<","<<**a<<endl;
return true;
}
and
call(&a);
or
(by reference)
bool call(int* &a) { // no further changes
Also, you have a memory leak: you loose the new ints you create (indeed it's
a small leak, but consider this: I was leaking 192bytes in a loop and in 2
minutes, I ate up all my 2Gb of RAM....)
Regards,
Jonathan
On 5/21/07, Lloyd <ll...@cd...> wrote:
>
> Hi ,
>
> This is a small program and its output
>
> #include<iostream>
> using namespace std;
>
> bool call(int *a)
> {
> static int x;
> ++x;
> int *temp=new int;
> *temp=x;
> a=temp;
> cout<<"call->"<<x<<","<<*a<<endl;
> return true;
> }
>
> int main()
> {
> int *a;
> for(int i=0;i<10;++i)
> {
> call(a);
> cout<<"val->"<<*a<<endl;
> }
> return 0;
> }
>
> Outputcall->1,1
> val->0
> call->2,2
> val->0
> call->3,3
> val->0
> ......
> ...
>
> The output which I wanted is
>
> Outputcall->1,1
> val->1
> call->2,2
> val->2
> call->3,3
> val->3
> .....
> ....
>
> The modification of the pointer in the function is reflected in the
> calling function. Would anybody tell me the reason for this mistake?
>
> Thanks and Regards,
> Lloyd
>
>
>
>
> ______________________________________
> Scanned and protected by Email scanner
>
> -------------------------------------------------------------------------
> This SF.net email is sponsored by DB2 Express
> Download DB2 Express C - the FREE version of DB2 express and take
> control of your XML. No limits. Just data. Click to get it now.
> http://sourceforge.net/powerbar/db2/
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www23.brinkster.com/noicys/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
--
<Morpheus> linux, c'est une question de VI ou de MORE
|