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.
变量的值t是一个或多个连续s的位置。char当您这样做时t = s,您将 char 的位置复制s[0]到(并替换来自t的旧值)。 现在指的是完全相同的字符 - 修改一个将通过另一个可见。tmalloc()t[0]s[0]
当您使用 时strcpy(t, s),您将实际字符从一个位置复制到另一个位置。
前者就像把两个门牌号放在同一个房子上。后者就像在一个房子里制作一个所有家具的精确复制品,然后把它放到第二个房子里。
strcpy()函数用于将一个字符串复制到另一个字符串,您在这里误用了它。使用指针时,您可以轻松地做到这一点,
t=s;
指针't'获取字符串's'的基地址,这就是指针的用途。另一方面,你strcpy工作。你让一个指针存储整个字符串。.