Re: How is memory allocated

"Samuel Thomas" <> wrote in message
news:...
| Could you please go through the code I wrote and help me with my
| doubts?
....
| 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?
Yes, it's perfectly ok here. Because the nam variable is accessed
by printnamesec *before* the exit of printnamefirst.

| When does it become unsafe to use variables declared in one function
| else where?

When a non-static (auto) variable is used/accessed after the exit
of the { .... } block in which it is declared.

| 2.Is it possible to make 'pass by value' work with character strings
| so that they dont get changed? Do they always get passed as reference
| values when passed across functions? Does the value of the nam
| variable declared in printnamefirst get modified because of the 'pass
| by reference' mechanism?

C strings are simple arrays of characters. When arrays are passed
as a parameter to a function call, they are converted to a pointer
to the array's first element.
void printnamesec(char ns[])
is actually equivalent to:
void printnamesec(char* ns)

Yes, when printnamesec changes the contents pointed to by ns,
it will modify the data held by the caller.

You can prevent the accidental modification of the caller's data
by using the const keyword:
void printnamesec( const char ns[] )
// will make assignment to ns[...] illegal

There is no simple way in C to pass arrays by value.
Except maybe if the array has a fixed size, and can be put
in a struct, which can then be passed by value:
struct Name { char name[16]; };
void f( struct Name name_ ); // param is passed by value

Share This Page

Welcome to The Coding Forums!

Welcome to the Coding Forums, the place to chat about anything related to programming and coding languages.

Please join our friendly community by clicking the button below - it only takes a few seconds and is totally free. You'll be able to ask questions about coding or chat with the community and help others.
Sign up now!