Advantage of using strcpy function in C
void main()
{
char s[100]="hello";
char *t;
t=(char*)malloc(100);
strcpy(t开发者_开发百科,s);
}
Alternatively, we could assign s
to t
like this: t=s;
. What is the disadvantage of using the alternative?
When using a simple assignment like t = s you are not actually copying the string, you are referring to the same string using two different names.
If you assign t=s
every change applied to the memory block pointed by t
will affect the s
which may not be what you want.
Also, you might want to look at this post.
The value of the variable t
is the location of one or more contiguous char
s. When you do t = s
, you are copying the location of the char s[0]
into t
(and replacing the old value of t
that came from malloc()
). t[0]
and s[0]
now refer to exactly the same character - modifying one will be visible through the other.
When you use strcpy(t, s)
, you are copying the actual characters from one location to another.
The former is like putting two house numbers on the same house. The latter is like making an exact replica of all the furniture in one house and placing it into the second.
strcpy()
function is used to copy one string to another,you mis-used it here.When working with pointers you could have easily done it like,
t=s;
pointer 't' gets the base address of the string 's' and that is what pointers are for.On the other hand you the strcpy work.You make a pointer store THE WHOLE STRING..
精彩评论