分配到另一个字符串串 [英] assigning a string to another string
问题描述
为什么这个code没有运行?为什么STR1没有分配给STR2?我知道我一直在使用的strcpy的选择,但我想知道这是为什么不工作的原因?
Why this code is not running? Why str1 is not assigned to str2 ?? I know i have an option of using strcpy but i wish to know the reason why this is not working??
#include<stdio.h>
int main()
{
char str1[]="hello";
char str2[10];
str2=str1;
printf("%s",str2);
return 0;
}
而如果我使用指针比它的工作原理是在这里..
Whereas if I use pointers than it works like here..
#include<stdio.h>
int main()
(
char *s="good morning";
char *q;
q=s;
while(*q!='\0')
{
printf("%c",*q);
q++;
}
return 0;
}
这工作。
现在,该字符串已通过指针复制,为什么这样的差异?
This works. Now the string has been copied via pointers so why such difference??
推荐答案
您需要做的
的strcpy(STR2,STR1)
您需要将 STR1
的每个元素复制到 STR2
逐个字符。
you need to copy each element of the str1
to str2
character by character.
你在做什么是试图在 STR1指定字符串的地址
分配给数组VAR STR2
这是不允许的。不能用于静态数组被分配的值。
What you are doing is to attempt assign the address of the string in str1
assign to the array var str2
which is not allowed. Static arrays couldn't be used to be assigned values.
即使你有的char * str2的;
然后 STR2 = STR1
虽然你的code会工作的,但在这种情况下,串中不 STR1复制,字符串代替地址
在 STR2复制
所以现在取消引用 STR2
将指向字符串
Even if you had char *str2;
and then str2 = str1
although your code would work, but in such a case the string is not copied, instead the address of the string in str1
is copied in str2
so now dereferencing str2
will point to the string
另外请注意,当您复制字符串转换成的char * str2的
总是复制之前,分配足够的内存。
一种可能性是:
Also note that when you copy string into a char *str2
always allocate enough memory before copy.
one possibility is:
str2 = malloc (sizeof (char) * (strlen (str1) + 1));
strcpy (str2, str1);
这篇关于分配到另一个字符串串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!