2013-04-09 116 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

相關問題