2013-04-09 65 views
0

出于某种原因,我得到一个编译错误,每当我尝试C字符串的值设置为一个字符串:C字符串的值设置为一个字符串

#include <stdio.h> 

int main(void) { 
    char hi[] = "Now I'm initializing a string."; 
    hi = "This line doesn't work!"; //this is the line that produced the compiler error 
    return 0; 
} 

而且,这些都是编译器错误:

prog.c: In function ‘main’: 
prog.c:5:8: error: incompatible types when assigning to type ‘char[31]’ from type ‘char *’ 
prog.c:4:10: warning: variable ‘hi’ set but not used [-Wunused-but-set-variable] 

我该怎么办才能解决这个问题?

+0

@OliCharlesworth看起来,另一个问题比这个更简单(而且不容易阅读),所以我不确定这些问题是否应该合并。 – 2013-04-09 19:59:16

回答

0

好吧,这里发生了什么是这样,

当你写

hi = "something here"; 

发生的事情是,在内存中,字符串“的东西在这里”被存储,并返回指针存储字符串的内存中的第一个元素。

所以,它期望左值是一个指向char的指针,而不是一个char数组本身。

所以,喜必须声明为char* hi

3

方式复制一个字符串是strcpy()功能:

strcpy(hi, "This line should work"); 

请注意:这并不检查是否有足够的空间在目标握住字符串。 (不,strncpy()可能是not the solution

C不容许阵列分配

推荐阅读:。在comp.lang.c FAQ第6

0

试试这个:

char hi[100]; 
strlcpy(hi, "something here", sizeof(hi)); 

你应该使用strlcpy()因为strcpy()strncpy()不安全。

参见:strncpy or strlcpy in my case

+0

使用'sizeof hi',而不是'100'。请注意,'strlcpy()'不是C标准的一部分(也不是POSIX),所以它可能会或可能不可用。 – 2013-04-09 19:59:48

+0

感谢您的反馈。我用sizeof(hi)取代了100。如果'strlcpy'不可用,也许OP可以使用'strcpy'。两者都可以成为问题的答案。如果有'strlcpy',最好是使用它。 – 2013-04-09 20:03:52

相关问题