0
#include <stdio.h>
void stringcopy(char *, char *);

int main(void) 
{

   char *a="akash";
   char *b;
   stringcopy(a,b);
   printf("%s",b);//why this is null? 
   return 0;
   }
 void  stringcopy(char*a,char*b)
{
     b=a;
     printf("%s\n",b);// it is not null
}

Blockquote in a function stringcopy ,i am getting output right. but after call i am getting null in main.why it is happening?please explain?

Akash
  • 3
  • 2
  • http://ideone.com/OHVEpw – Akash Jan 05 '15 at 00:05
  • In main, you won't see the change, as you are only changing `b` in `stringcopy` in the scope of `stringcopy` – Ryan Jan 05 '15 at 00:14
  • I guess it happens because in the stringcopy function the function parameters are copied. So u need to pass a pointer to a pointer to modify them. – TrezzJo Jan 05 '15 at 00:18

1 Answers1

3

It doesn't work after stringcopy returns, because in C function arguments are passed by value, so b will remain unmodified (assignment was made on local copies of a and b). It is only modified within function. Read about call stack.

Pass addresses of a and b to stringcopy and dereference them inside function.

#include <stdio.h>

void stringcopy(char**, char**);

int main(void) 
{
   char *a = "akash";
   char *b;
   stringcopy(&a, &b);
   printf("%s\n",b);
   return 0;
}

void  stringcopy(char** a,char** b)
{
     *b = *a;
     printf("%s\n", *b);
}

Note that this will only make b to point to the memory region where string literal "akash" is stored, so that's not exactly copying string.

macfij
  • 3,093
  • 1
  • 19
  • 24
  • This fixes one major OP problem, but a weakness remains. `a` points to a `const char *`. The suggested `stringcopy()` results in `char *b` also pointing to the same `const char *`. In this snippet, no big deal though. – chux - Reinstate Monica Jan 05 '15 at 01:05