Scoping question in C

Adil Kodian akodian-Re5JQEeQqe8AvxtiuMwx3w at public.gmane.org
Thu Jun 9 23:43:43 UTC 2005


Actually your code wont work right away - (its been a long time since ive
done C but this is what I recall)(im assuming that you havent declared x
before the main function and declared it glob.

x = (char *)malloc(sizeof(char)*80) 

Is necessary at some place if you want the string to be 80 chars long
(remember the \0). Alternatively you can calloc or realloc when necessary. 

If you malloc this part in the main function  then you can use what you have
below. To be able to say x="dsadasd" in func() you need to pass func(x)
where the prototype is int func(char* x);

If you only declare char *x in the main (or for that matter outside main)
and malloc in func(x) keep in mind that when you exit from func(x) that
memory is destroyed but the pointer stays alive - in C you must specifically
free(x); in C++ you must delete() if you created with new(). Use Java and
you don't have to muck around with this at all. 

If you declare and malloc x in func() then you can do whatever you want with
x inside func, but the moment you exit, the memory and the pointer
associated with that space is destroyed (or zombied - depending on your OS).
(mind you the data itself may not be destroyed and anyone can technically
retrieve it - but that is microsoft's forte :-) )



-----Original Message-----
From: owner-tlug-lxSQFCZeNF4 at public.gmane.org [mailto:owner-tlug-lxSQFCZeNF4 at public.gmane.org] On Behalf Of William Park
Sent: Thursday, June 09, 2005 4:49 PM
To: TLUG-lxSQFCZeNF4 at public.gmane.org
Subject: [TLUG]: Scoping question in C

I have question regarding scope of static string inside C function.
Suppose I have

    char *x;

    int func ()
    {
	x = "something";
	return (1);
    }

where 'x' is global variable being used elsewhere.  Can I use 'x' after
func() exits?  That is, is 'x' still pointing to string "something"?

--
William Park <opengeometry-FFYn/CNdgSA at public.gmane.org>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
	   http://home.eol.ca/~parkw/thinflash.html
--
The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns How to
UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml

--
The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml





More information about the Legacy mailing list