我有以下函数,我以前在 C 程序中使用过很多次:
/**
Splits a given string into an array of strings using given delimiters.
@param input_string
The string to be split.
@param delimiters
The characters that will be used as delimiters.
@return
The components of the split string followed by @c NULL , or only
@c NULL if sufficient memory fails to allocate for the returned array.
*/
char **split(char *input_string, const char *delimiters) {
char **components = NULL;
int components_count = 0;
char *component = strtok(input_string, delimiters);
while (component) {
++components_count;
// |components| is reallocated to accomodate |component|. If
// |realloc()| fails, |NULL| is returned.
components = realloc(components, sizeof(char *) * components_count);
if (!components) return NULL;
components[components_count - 1] = component;
component = strtok(NULL, delimiters);
}
// |components| is reallocated once more to accomodate an additional
// |NULL|. Only |NULL| is returned in |realloc()| fails.
components = realloc(components, sizeof(char *) * (components_count + 1));
if (!components) {
return NULL;
}
components[components_count] = NULL;
return components;
}
我最近刚刚将该函数添加到一个 C++ 项目中,以便在我需要处理 C 字符串的情况下使用。编译时,我现在得到这个错误:
error: assigning to 'char **' from incompatible type 'void *'
components = realloc(components, sizeof(char *) * components_count);
error: assigning to 'char **' from incompatible type 'void *'
components = realloc(components, sizeof(char *) * (components_count + 1));
我完全不知道如何处理这些错误。就我而言,我正在做的事情在 C++ 中应该是合法的,因为它在 C 中始终运行良好。有什么见解吗?
如果有帮助,我在 OS X 上使用 clang++ 作为编译器,但这段代码也可以在 Ubuntu 上使用 g++ 编译。
最佳答案
在 C 和 C++ 上并非所有内容都必须相同; malloc
和 realloc
就是一个常见的例子。
- 您不必在 C 中显式转换
void pointer
,它将自动完成,如您的示例所示。 - 您肯定必须在 C++ 中显式转换该指针,包括
malloc
和realloc
函数。
这两种语言之间存在很大差异,不要想当然。
在此链接中,说明了 C 和 C++ 之间在基本内容上的一些差异;可能值得一读。
http://www.cprogramming.com/tutorial/c-vs-c++.html
或者这个(由评论建议):
关于c++ - 为什么 realloc() 在为 C++ 编译时神秘地表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29452720/