簡體   English   中英

編譯錯誤

[英]Compiling errors

我正在嘗試編譯但卻收到以下錯誤:

1>.\item.cpp(123) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)

1>.\commands.cpp(1372) : error C2057: expected constant expression
1>.\commands.cpp(1372) : error C2466: cannot allocate an array of constant size 0
1>.\commands.cpp(1372) : error C2133: 'buffer' : unknown size

123行item.cpp

if((bool)random_range(0, 1))

第1372行

if(money < changeSexPrice)
{
char buffer[70 + changeSexPrice];
sprintf(buffer, "You do not have enough money. You need %d gold coins to change your sex.", changeSexPrice);
player->sendCancel(buffer);
return false;
}

任何想法?

您的問題是char buffer[70 + changeSexPrice]; 在進行堆棧分配時,win32編譯器需要一個常量表達式。

我不確定為什么要添加changeSexPrice,因為僅使用緩沖區來打印int。 我敢打賭,如果您選擇諸如char buffer[1024]類的東西,那么您的需求將綽綽有余。

編輯:根據評論(這是非常好的)。

如果您使用固定大小為len 1024的緩沖區,請使用snprintf。 在Visual Studio的情況下,這是sprintf_s 您的代碼將更改為:

sprintf_s(buffer, 1024, "You don't have enough money ...", yourValueHere);

另外, Mark B提出的答案也消除了您自己分配內存的需求。

聲明基於堆棧的可變長度數組是gcc擴展(可能還有其他擴展)。 使用ostringstream進行格式化:

if(money < changeSexPrice)
{
    std::ostringstream os;
    os << "You do not have enough money. You need " << changeSexPrice << " gold coins to change your sex.";
    player->sendCancel(os.str().c_str());   // This assumes that sendCancel doesn't take ownership of its parameter.
    return false;
}
if((bool)random_range(0, 1))

最好這樣寫:

if(random_range(0, 1) == 1)

這更清楚,警告將消失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM