Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   Re: How is memory allocated (http://www.velocityreviews.com/forums/t313867-re-how-is-memory-allocated.html)

bd 06-27-2003 01:49 PM

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
> doubts?
>
>
> #include <stdio.h>
> #include <conio.h>


Non-standard header.

>
> void printnamefirst(char[]);
> void printnamesec(char[]);
>
> void main()


main() returns int. *ALWAYS*.

> {
> clrscr();


Non-standard function

> printnamefirst(name);


Where's name declared?

return 0;

> }
>
> void printnamefirst(char nm[])
> {
> char nam[20] ="Samuej Thomas";
> printnamesec(nam);
> printf("%s \n",nam);
> }
>
> void printnamesec(char ns[])
> {
> printf("%s \n",ns);
> ns[5]='l';
>
> }
>
> 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[20] = "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?


Yes.
--
Freenet distribution not available
GIVE: Support the helpless victims of computer error.



All times are GMT. The time now is 03:06 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.