Gopi Krishna Komanduri <[EMAIL PROTECTED]> wrote:
>
> Hi,
> I have a small query ..like whenever any variable is
> declared and used in one function , then scope won't be there
> outside of that function.
Yes.
> Then how will be case with pointers?
Exactly the same, but you have to be careful when talking
about the pointer value and talking about what it points to.
> like..
> #influde<stdio.h>
> char * fun()
> {
> char *x="Gopi"; // -->Is this initialisation correct?
Strictly speaking no. The initialisation does not require
a diagnostic and is well defined (in C), but you should
realise that although the string has static storage duration,
it cannot be modified without invoking undefined behaviour.
Better would be...
const char *fun()
{ return "Gopi"; }
> return x;
> }
> main()
I'm surprised you got this to compile on a C++ compiler.
Unlike C90, C99 and C++ no longer support implicit int
declarations.
int main(void)
> {
> char *k=new char(5);
Not much point allocating stuff to point to if you're going to
clobber it with the next line.
> k=fun();
> }
> Here k got value "Gopi";
It got a pointer to that string, yes.
> But x is declared only in function "fun()".
Yes, x goes out of scope, but the object it pointed to has
static duration (lifetime of the program), so it still
exists.
> Does it mean , for variables whose memory allocated in
> heap instead of stack will remain till the end of program?
Here's your biggest problem. And you're not the only one
to make this fundamental mistake. You're more concerned
about _where_ things are stored, when the language is in
fact defined in terms of _when_.
Obviously you recognise the 'when' component, but you're
trying to reconcile that against 'where' you think things
are stored. You're much better off recongising when objects
exist from their declarations in context. Where the are
stored behind the scenes is completely incidental.
A significant example is the alloca function available
under POSIX, or the variable length array available in
C99. The objects allocated can exist in either a
hardware stack or the dynamic heap allocation behind
the scenes, but their lifetime is always bounded by the
end of the function block.
--
Peter