声明一个指针并将 realloc 的结果分配给它作为 if 参数在 C 中有效吗?
Is declaring a pointer and assigning the result of a realloc to it as an if argument valid in C?
我正在尝试实现Dijkstra算法,首先需要设计一个节点数可变的图结构;为此,我需要动态更改结构数组的大小,我想知道是否要这样写:
if( !(struct s *a = (struct s *)realloc(some_pointer_to_s_struct, new_size*sizeof(struct s))) ) {
return -1; //because that means my pointer is NULL
}
//do something
在 C 中是正确的,因为根据这个 post : answer to a post on the subject 它是。
然而,当我尝试更改我的代码以匹配该模式时,我遇到了很多 error: expected ‘)’ before xxx
和其他类似的错误...
我想也许我一开始忘记匹配括号或括号,但我花了 30 分钟检查我的代码,这似乎不是问题。
这个问题是关于 C++ 的,而不是关于 C 的。在 C 中这是不可能的。
顺便说一句,您的代码也不是有效的 C++,因为它试图对声明使用否定。
我正在尝试实现Dijkstra算法,首先需要设计一个节点数可变的图结构;为此,我需要动态更改结构数组的大小,我想知道是否要这样写:
if( !(struct s *a = (struct s *)realloc(some_pointer_to_s_struct, new_size*sizeof(struct s))) ) {
return -1; //because that means my pointer is NULL
}
//do something
在 C 中是正确的,因为根据这个 post : answer to a post on the subject 它是。
然而,当我尝试更改我的代码以匹配该模式时,我遇到了很多 error: expected ‘)’ before xxx
和其他类似的错误...
我想也许我一开始忘记匹配括号或括号,但我花了 30 分钟检查我的代码,这似乎不是问题。
这个问题是关于 C++ 的,而不是关于 C 的。在 C 中这是不可能的。
顺便说一句,您的代码也不是有效的 C++,因为它试图对声明使用否定。