cp**********@yahoo.com said:
Could some C guru please help me? Suppose I have a code snippet as:
int* doit(){
int intArray[25];
int *ip;
ip = intArray;
return ip;
}
Since the array intArray is allocated on the stack
More precisely, the array intArray is an automatic object.
and so destroyed
when function returns, is it safe to say that at compile time it is
not known what ip points to?
At compile time, it doesn't point anywhere, because at compile time the
program isn't running!
When the function returns, the returned pointer is of no use, as you rightly
surmise, because the object to which it points (the first int in the array)
no longer exists. (Nor do the other ints in the array, of course!)
Solutions:
a) pass the address of the first array element as an argument;
b) create the space for the array dynamically;
c) make intArray static.
Of these, c) is the worst choice, in my opinion; b) is better, but you ought
to free the allocated memory when you're finished with it; a) is probably
the simplest choice.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)