[英]string literal in c
為什么以下代碼是非法的?
typedef struct{
char a[6];
} point;
int main()
{
point p;
p.a = "onetwo";
}
它與文字的大小有關嗎? 還是在聲明字符串后將字符串常量分配給char數組是非法的?
它與大小無關。 創建字符串文本后,不能將其分配給char數組-您只能在定義時使用它。
當你做
char a[] = "something";
它創建一個足夠大的數組(包括終止null)並將字符串復制到該數組。 用字符串文字初始化數組大小時,最好不要指定它的大小-可能不考慮空字符。
當你做
char a[10];
a = "something";
您正在嘗試分配給數組的地址,這是非法的。
編輯:如其他答案中所述,您可以執行strcpy / strncpy,但要確保使用所需的長度初始化數組。
strcpy(p.a, "12345");//give space for the \0
創建數組后,您再也無法分配它們了; 這同樣是非法的:
int foo[4];
int bar[4];
foo = bar;
您需要使用指針,或分配給數組的索引。 這是合法的:
p.a[0] = 'o';
如果要在結構中保留一個數組,可以使用類似strcpy
的函數:
strncpy(p.a, "onetwo", 6);
(請注意,char數組必須足夠大以容納nul-terminator,因此您可能希望將其設為char a[7]
並將最后一個參數更改為strncpy
為7)
數組是non modifiable lvalues
。 因此,您無法分配給他們。 賦值運算符的左側必須是modifiable lvalue
。
但是,可以在定義數組時初始化它。
例如 :
char a[] = "Hello World" ;// this is legal
char a[]={'H','e','l','l','o',' ','W','o','r','l','d','\0'};//this is also legal
//but
char a[20];
a = "Hello World" ;// is illegal
但是,您可以使用strncpy
(a, "Hello World",20);
正如其他答案已經指出的那樣,您只能使用字符串文字初始化字符數組,而不能將字符串文字分配給字符數組。 但是,結構(即使是那些包含字符數組的結構)也是另一回事。
我不建議在實際程序中執行此操作,但這表明盡管不能將數組類型分配給包含數組類型的結構,但是可以。
typedef struct
{
char value[100];
} string;
int main()
{
string a = {"hello"};
a = (string){"another string!"}; // overwrite value with a new string
puts(a.value);
string b = {"a NEW string"};
b = a; // override with the value of another "string" struct
puts(b.value); // prints "another string!" again
}
因此,在您的原始示例中,以下代碼應可以正常編譯:
typedef struct{
char a[6];
} point;
int main()
{
point p;
// note that only 5 characters + 1 for '\0' will fit in a char[6] array.
p = (point){"onetw"};
}
請注意,為了將字符串“ onetwo”存儲在數組中,它的長度必須為[7],而不是問題中所寫的那樣。 多余的字符用於存儲'\\ 0'終止符。
不需要任何strcpy或C99 compund文字。 純ANSI C中的示例:
typedef struct{
char a[6];
} point;
int main()
{
point p;
*(point*)p.a = *(point*)"onetwo";
fwrite(p.a,6,1,stdout);fflush(stdout);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.