Re: How is memory allocated
On Fri, 27 Jun 2003 04:35:39 -0700, Samuel Thomas wrote:
> Hello Everybody,
> Could you please go through the code I wrote and help me with my
> #include <stdio.h>
> #include <conio.h>
> void printnamefirst(char);
> void printnamesec(char);
> void main()
main() returns int. *ALWAYS*.
Where's name declared?
> void printnamefirst(char nm)
> char nam ="Samuej Thomas";
> printf("%s \n",nam);
> void printnamesec(char ns)
> printf("%s \n",ns);
> 1.Is it safe to use the variables that are allocated in one function,
> in another function as I have done by printing a string in the
> printnamesec, but which has been declared in printnamefirst function?
In this case, yes.
> When does it become unsafe to use variables declared in one function
> else where?
Until program control leaves the scope it's defined in. In this case,
until the function returns. If it was declared inside a another set of
braces, until the program leaves that block.
However, if you declare it with 'static', it can be accessed as long as
you want eg:
static char foo = "bar";
However, now there's only one foo for each time the function's called, so
it'll only be "bar" until it gets modified.
> 2.Is it possible to make 'pass by value' work with character strings
> so that they dont get changed?
You could put it in a struct, but using const is better:
void foo(const char *bar);
The compiler will complain if you attempt to modify *bar in there (but
modifying bar is OK)
> Do they always get passed as reference
> values when passed across functions?
They should be. It's possible to pass by value, but you must specify a
compile-time size limit, and it'll probably be slow.
> Does the value of the nam
> variable declared in printnamefirst get modified because of the 'pass
> by reference' mechanism?
Freenet distribution not available
GIVE: Support the helpless victims of computer error.
|All times are GMT. The time now is 09:28 PM.|
Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.