nafiz amin
nafiz amin

Reputation: 97

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?

Upvotes: 1

Views: 736

Answers (4)

user379888
user379888

Reputation:

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..

Upvotes: 0

caf
caf

Reputation: 239321

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.

Upvotes: 1

asandroq
asandroq

Reputation: 575

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.

Upvotes: 5

khachik
khachik

Reputation: 28703

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.

Upvotes: 1

Related Questions