Reputation: 21
#include<stdio.h>
#include<stdlib.h>
char *str_cpy(char *, char *);
void main()
{
char *desti= (char *)calloc(sizeof(char),10);
char *m= (char *)calloc(sizeof(char),10);
m = str_cpy(desti,"dhawal");
printf("destination string is :%s\n",desti);
printf("%s\n",m);
}
char *str_cpy(char *a,char *b)
{
while(*b!='\0')
{
*a = *b;
a++;
b++;
}
*a = '\0';
return a;
}
Please explain why m
is not assigned with value of desti
here?
It assigns a value to a third variable the result of string copy
Upvotes: 1
Views: 144
Reputation: 60007
desti
will contain "dhawal"m
will point to the null character of that string. That is the same value as a
at the end of str_cpy
To avoid this use
char *str_cpy(char *a,char *b)
{
char *r=a;
while(*b!='\0')
{
*a = *b;
a++;
b++;
}
*a = '\0';
return r;
}
Upvotes: 6