【发布时间】:2015-01-31 16:07:35
【问题描述】:
我想将if 语句与malloc() 函数一起使用。
我有这个代码:
if(uint16_t *buf = (uint16_t *) malloc(data_len*2) == NULL) exit(1);
但我得到了错误:
error: cannot convert 'bool' to 'uint16_t*' in assignment
我错了还是我必须更改代码?
这是带有括号等的原始代码:
if ((data = malloc(data_len)) == NULL ||
(buf = malloc(data_len*2)) == NULL) {
exit(1);
}
【问题讨论】:
-
首先,决定一种编程语言。您提到的代码在任何一个中都不好,但是出于不同的原因。也就是说,错误是由评估各种运算符的顺序引起的,这不是您想要的。
-
添加一对括号
if((uint16_t *buf = (uint16_t *) malloc(data_len*2)) == NULL) -
如前所述,C++ 中不需要 malloc()。那是 C 的东西。
-
@UlrichEckhardt 原来的 C 代码是这个,buf = malloc(data_len*2)== NULL 我问社区stackoverflow.com/questions/28226016/… 如何在 C++ 中做到这一点。
-
然后使用 std::vector
。它将使用异常发出分配失败的信号,因此您不会因无用的检查而使代码混乱。也就是说,您应该在 C++ 中使用 static_cast,但其他 cmets 是正确的,首先不要在那里使用 malloc()。顺便说一句:考虑你的版本中 buf的范围!