int main()
{
char *a;
a= malloc(20);
strcpy("a,"India"");
change(a);
printf("%s\n",a);
}
void change (char *b)
{
b="Testing";
}
The o/p of this program is India. can any one tell how this works.
It doesn't work. The output, if any, is completely random, since your
code has gross errors. See below:
#include <stdio.h> /* mha: added. Needed for the variadic
function printf */
#include <stdlib.h> /* mha: added. Needed because malloc
returns a pointer-to-void, not an
int as your code implies (in C89,
things are worse under C99). */
#include <string.h> /* mha: added, for strcpy, which
returns a pointer-to-char, not an
int as your code implies. */
void change(char *); /* mha: needed, since your main expects
change to return an int. */
void new_change(char *); /* mha: a new version of change */
int main(void)
{
char *a;
if (!(a = malloc(20))) {
fprintf(stderr, "Malloc failed. Quiting ...\n");
exit(EXIT_FAILURE);
}
strcpy(a, " India "); /* mha: fixed the grossly incorrect
original 'strcpy("a," India "");' */
printf("contents of array pointed to by a: \"%s\"\n", a);
change(a);
printf("OP's change produces no change in a: \"%s\"\n", a);
new_change(a);
printf("mha's new_change does change a: \"%s\"\n", a);
free(a); /* mha: added. failure to free what you
allocate is a sin. */
return 0; /* mha: added for C89, and for sanity
since a function returning an int
should return one */
}
void change(char *b)
{
b = "Testing"; /* mha: changes the local value of the
pointer b, a copy of a in main */
}
void new_change(char *b)
{
strcpy(b, "Testing"); /* mha: changes the array whose first
element is pointed to by b */
}
[output]
contents of array pointed to by a: " India "
OP's change produces no change in a: " India "
mha's new_change does change a: "Testing"