First, let us not top-post in this group. Luckly I never got a warning
regarding this till now.
Doug said:
Hi All,
Sorry for the confusing post. Here is code that compiles:
void doIt(int* x){
int b = 2;
x = &b;
}
int _tmain(int argc, _TCHAR* argv[])
{
int* a = NULL;
doIt(a);
printf("a = %d", *a); // blows up
return 0;
}
I think I have two issues:
1. int b in doIt() goes out of scope when the function returns, so its
address is no longer valid when we get back to _tmain().
OK, we have already discussed about local varialbles. We should not
return the address of the local variable. because it dies after the
function execution. but a doesn't get the address of b. it still is
zero.
However even
if I rewrite doIt() as:
void doIt(int* x){
x = new int;
*x = 2;
}
It still fails which brings me to:
2. I think what I really want is for doIt() to take an int**. I think
the reason is that if it takes int *, it's actually getting a copy of
the pointer in _tmain, so allocating space and assigning a value to
this new pointer doesn't do me any good.
you are almost right. In main, we have declared pointer a and assigned
it to NULL (zero).
a's work is to point to some address and a is also created with some
address (&a).
so &a will have some address (system created)
our a points to zero. we assigned.
now in function doIt(int *x), x takes zero. not &a. and ofcourse x will
have it's own address (&x), that is no where related to &a. now &x and
&a are different.
in x = new int; x gets a value which is no where related to a. So when
doIt() completes it's execution, a will still point to zero. That is
why it fails.
However, if I rewrite the
program as below it works. Does this make sense?
void doIt(int** x){
*x = new int;
int b = 2;
**x = b;
}
int _tmain(int argc, _TCHAR* argv[])
{
int* a = NULL;
doIt(&a);
printf("a = %d", *a); // prints "a = 2"
return 0;
}
it makes sense. it should take the address of a, where a is a pointer
so we have to take pointer to pointer.
with the above explanation again. "new int" allocates memory. The point
is where it is allocating memory. For sure, it is allocating memory for
a. It is not local to function doIt().
Finally, the below also works, but I think it's *bad* because I think I
shouldn't use an address from another function. Do you agree?
void doIt(int** x){
*x = new int;
int b = 2;
*x = &b;
}
It worked because you are not manupulating any data in &b after the
function execution. but are you getting 2 in the result?
in my knowledge the results are undefined.
This is program logic error.
HTH.
-- Murali Krishna.