valleytech
asked on
Explaination
Hi all,
I have
#include <stdio.h>
#include <stdlib.h>
void check( int * &ptr)
{
int *tmp;
tmp = (int*)malloc(sizeof(int));
*tmp= 100;
ptr= tmp;
printf("in check is %d\n",*tmp);
}
void main ()
{
int* t;
check(t);
printf("value is %d\n",*t);
}
/*
in check is 100
value is 100
Press any key to continue
*/
I just wonder that the tmp in chec() is a local variable. So have can its value still valid for t in main() , even though i know ptr = tmp. Please explain me the
check (int * &ptr) vs check( int *ptr). More examples are appreciated.
Thanks.
I have
#include <stdio.h>
#include <stdlib.h>
void check( int * &ptr)
{
int *tmp;
tmp = (int*)malloc(sizeof(int));
*tmp= 100;
ptr= tmp;
printf("in check is %d\n",*tmp);
}
void main ()
{
int* t;
check(t);
printf("value is %d\n",*t);
}
/*
in check is 100
value is 100
Press any key to continue
*/
I just wonder that the tmp in chec() is a local variable. So have can its value still valid for t in main() , even though i know ptr = tmp. Please explain me the
check (int * &ptr) vs check( int *ptr). More examples are appreciated.
Thanks.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi Axter,
How can the local variable still there after exit the check(). So far I know that local variable only still avaible if i use static.
One more thing, if i use
printf("value is %d\n",t) ---> it doesn't work. COuld you please explain line by line? Thanks a lot.
How can the local variable still there after exit the check(). So far I know that local variable only still avaible if i use static.
One more thing, if i use
printf("value is %d\n",t) ---> it doesn't work. COuld you please explain line by line? Thanks a lot.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Wow,
It's clear now Kdo. Thanks.
It's clear now Kdo. Thanks.
> Please explain me the check (int * &ptr).
That is not C code, and instead that is C++ code.
In C++ that's a reference to a pointer, and it allows it to change the calling functions variable as to what it's pointing to.
You can't do that with C unless you use a pointer to a pointer.
Cheers!