开发者

Advantage of using strcpy function in C

开发者 https://www.devze.com 2023-01-29 18:42 出处:网络
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 altern
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 chars. 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..

0

精彩评论

暂无评论...
验证码 换一张
取 消