On 4 Apr 2005 16:38:38 -0700
jrefactors@hotmail.com wrote:
[color=blue]
> In the following program, are parameters s in function
> reverse() and x in function count() both pass by value? How
> come value k is not changed, but value str has changed?
>
> Please advise.
> thanks!!
>
> ============================================
> void reverse(char s[]);
> void count(int x);
>
> int main(void)
> {
> char str[] = "hello";
> int k = 10;
> printf("before str = %s\n", str);
> reverse(str);[/color]
Here, you pass the value of the adress of the first element of
str[], then reverse() changes the array str. So it changes the
string "hello" pointed by str.
This is still passing by value, but since you pass the
memory address of where the array of chars is, reverse() changes
what's there.
[color=blue]
> printf("after str = %s\n", str);
> printf("before k = %d\n", k);
> count(k);[/color]
Here you pass the value of k, but since this is an integer,
count() adds 5 to x, so x = 15 in count() and when count()
returns, k hasn't changed.
To make count() change k outside, you could do count(int *x),
call count(&k) and do *x = *x + 5 inside count() and this will
change k. Notice that I write *x, I mean the value of whatever x
is pointing to.
I hope I'm correct here and I hope that clarifies. With the
changes I suggest, you'd get:
%./rev
before str = hello
after str = olleh
before k = 10
after k = 15