Re: PLEASE HELP - Fundamental C language question
- From: Richard Heathfield <invalid@xxxxxxxxxxxxxxx>
- Date: Sun, 30 Oct 2005 03:10:24 +0000 (UTC)
cpptutor2000@xxxxxxxxx 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)
.
- References:
- PLEASE HELP - Fundamental C language question
- From: cpptutor2000
- PLEASE HELP - Fundamental C language question
- Prev by Date: Re: PLEASE HELP - Fundamental C language question
- Next by Date: Re: "a < b < c" not the same as "(a < b) && (b < c)"?
- Previous by thread: Re: PLEASE HELP - Fundamental C language question
- Next by thread: Re: C++ runtime errors, can someone help plz
- Index(es):
Relevant Pages
|