2010-07-16 187 views
0

我试着去编译,但即时得到这些错误:编译错误

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 commands.cpp

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; 
} 

什么想法?

+4

回答在win32标记中花费%d金币。阅读错误消息。 – 2010-07-16 12:55:40

+1

只是出于好奇:我需要多少金币来改变我的性别? – ereOn 2010-07-16 13:15:42

回答

2

你的问题是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 presents an answer,消除对自己的MEM分配的需要,以及。

+4

或者,因为这是C++,请使用'std :: string'并避免手动分配内存。 – 2010-07-16 13:01:56

+1

如果你打算建议一个固定的缓冲区大小,至少要坚持'snprintf'。你永远不知道代码何时被复制和/或改变,以及你分配的任何固定长度是不够的。 – 2010-07-16 13:59:44

+0

感谢您的意见。相应更新。 – 2010-07-16 14:22:47

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

最好写一样的东西:

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

这是更清晰,并警告将消失。

+0

更好(也许更正确)是'if(random_range(0,1))' – 2010-07-16 13:04:08

+0

不是更好,因为'random_range'的结果是一个硬币翻转,本身不具有布尔值的意义:不得不问“头部还是尾巴?”第一。不是更正确的,因为它做了一些不同于原始代码。 (注意:假设'random_range'产生整数值,如果它产生浮点值,那么这个代码就会被破坏。) – Thomas 2010-07-16 13:13:14

+0

实际上,Alexandre的代码和原始代码完全一样,if'(random_range(0 ,1)!= 0)'。只有函数只返回'0'或'1',你的函数才会这样。 – 2010-07-16 13:20:12

1

声明基于可变长度堆栈的数组是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; 
} 
+0

关于这个假设:原始代码做出了相同的假设。 – 2010-07-16 13:23:49