Re: Doubt



vhanwaribrahim@xxxxxxxxx wrote:

Hi all,

please see the below code.

int main()

int main(void) is better.

{
char *a;
a= malloc(20);
strcpy("a,"India"");

This is a syntax error. You probably meant to write:

strcpy(a, "India");

change(a);
printf("%s\n",a);

A return statement is better practise.

}

void change (char *b)
{
b="Testing";

}

The o/p of this program is India. can any one tell how this works.

This is because of the pass by value semantics of C. In C function
arguments are actually copied before the function is called. For
example:

void foo(void) {
int b = 10;
void bar(int);

bar(b);
printf("%d\n", b);
return;
}

void bar(int b) {
b = 20;
return;
}

Here a temporary copy of the object 'b' in foo() is created when the
function call to bar() takes place. The 'b' in bar() is local to that
function and any changes to it does not affect foo()'s copy of 'b'.
This is the case for all function arguments in C, except the case of
arrays. Here the array name decays to a pointer value to the array's
first element.

To enable a function to change it's caller's objects, you need to pass
pointers to them. This is automatically done in the case of arrays,
unless they are wrapped into structures.

.



Relevant Pages