I am presently new to programming and am following the C language which is being taught to us in our College.
I have doubt in the actual functioning of the strcpy()
function under the header-file #include<strings.h>
The general use of this function is given below -
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char a[] = "google";
char *b = (char*)malloc((strlen(a) +1)*sizeof(char));
strcpy(b,a);
printf("%s, %s\n", a, b); //prints google, google
free(b);
}
We are given the following format and prototype of the same :
char *strcpy( char *to, const char *from)
{
char *temp = to;
while (*to++ = *from++);
return temp;
}
I have a couple of doubts about this-
What is an extra pointer ( temp ) requirement in the function? Can't we just
return to;
at the end of the function?I convinced myself that the temp variable is used because during each while loop, the pointer
to
is changing itself. That is first*to
will be assigned*from
and thento = to +1
, andfrom = from +1
, will take place which will result in changing the address stored in the pointerto
. But if this is true, then what about the pointerfrom
? Will, it also not change at the end of thestrcpy()
function?Where is the function returning the address stored in temp? ( the function should only work if
b = strcpy(b,a);
be mentioned not onlystrcpy(b,a);
)
To check the given function I also made my own function "strcpy_me" and used it with the same format and prototype, and it gave the same results.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *strcpy_me( char *to, const char *from)
{
char *temp = to;
while (*to++ = *from++);
return temp;
}
int main()
{
char a[] = "google";
char *b = (char*)malloc((strlen(a) +1)*sizeof(char));
strcpy_me(b,a);
printf("%s, %s\n", a, b); // prints google, google
free(b);
}
Please help me clarify my doubt.