![](/img/trans.png)
[英]error C2440: '=' : cannot convert from 'const char [2]' to 'char'
[英]error C2440: '=' : cannot convert from 'int' to 'char [5]'
錯誤C2440:“ =”:無法從“ int”轉換為“ char [5]”幫助我)
char type[5];
switch (rec[n-1].recptr->qtype)
{
case 'p':type='pcs'; break; //here is problem
case 'm':type='kgs'; break; // and here is too
default: printf("incorrect code");break;
}
首先,串進去雙引號"
,而不是單引號'
。其次,要分配給char[]
數組你必須使用像函數strcpy()
你不能直接分配到一個數組=
。
case 'p': strcpy(type, "pcs"); break;
case 'm': strcpy(type, "kgs"); break;
首先, 'pcs'
是一個字符常量,而您需要一個字符串。 語法為"pcs"
。
而且, type
是一個數組,因此當不與sizeof
, _Alignof
或一元&
運算符一起使用時,它會衰減為指針,並且不是左值。 因此,您不能重新分配type
。
strcpy
可能是一個解決方案。
#include <string.h>
char type[5];
switch (rec[n-1].recptr->qtype)
{
case 'p':
strcpy(type,"pcs");
break;
case 'm':
strcpy(type,"kgs");
break;
default:
printf("incorrect code");
break;
}
或者,使用字符串垃圾(如果您不修改type
):
const char *type;
switch (rec[n-1].recptr->qtype)
{
case 'p':
type="pcs";
break;
case 'm':
type="kgs";
break;
default:
printf("incorrect code");
break;
}
C11(n1570),第6.3.2.1節L值,數組和函數指示符
除非它是
sizeof
運算符,_Alignof
運算符或一元&
運算符的操作數,或者是用於初始化數組的字符串文字,否則將類型為“ array of type”的表達式轉換為帶有鍵入“指向類型的指針”,它指向數組對象的初始元素,而不是左值。
'pcs'
是int
類型的多字符文字。
type
是一個數組。 您不能使用=
將任何東西分配給整個數組。
[從技術上講,在該表達式type
其行為相當於指向數組第一個元素的不可修改的指針,但是您不能修改不可修改的值。
使用strcpy(type,“ pcs”)和strcpy(type,“ kgs”)或std:string,您不能僅通過賦值來復制數組中的字符!
請使用strcpy,您不能使用=分配給char [5]
case 'p': strcpy(type, "pcs"); break;
但是如果您想避免使用strcpy(即使在這種理論上安全的情況下),也可以通過以下方式進行操作:
/* partial copy (only 3 chars): */
strncpy ( type, "pcs", 3 );
type[4] = '\0'; /* null character manually added */
如果您可以保持sizeof(int)個字符以下,則可以執行以下操作:
int type;
switch (rec[n-1].recptr->qtype)
{
case 'p':type='pcs'; break; //here is problem
case 'm':type='kgs'; break; // and here is too
default: printf("incorrect code");break;
}
上面的代碼未經測試,盡管我確實對此進行了測試:
int main( int argc, char **argv)
{
int t;
t = 'abcd';
printf ("t = %x\n", t);
t = 'dcba';
printf ("t = %x\n", t);
}
[347] ~/tmp: ./a.out
t = 61626364
t = 64636261
盡管這里您不必使用> sizeof(int)字符,但您實際上必須要小心。 我懷疑每個編譯器的實際運行情況可能會有所不同。 使用此方法可以消除其他答案中所有多余的字符串擔憂。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.