gpt4 book ai didi

c++ - 为什么 realloc() 在为 C++ 编译时神秘地表现不同?

转载 作者:太空宇宙 更新时间:2023-11-03 10:27:13 24 4
gpt4 key购买 nike

我有以下函数,我以前在 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++ 上并非所有内容都必须相同; mallocrealloc 就是一个常见的例子。

  1. 您不必在 C 中显式转换 void pointer,它将自动完成,如您的示例所示。
  2. 您肯定必须在 C++ 中显式转换该指针,包括 mallocrealloc 函数。

这两种语言之间存在很大差异,不要想当然。

在此链接中,说明了 C 和 C++ 之间在基本内容上的一些差异;可能值得一读。

http://www.cprogramming.com/tutorial/c-vs-c++.html

或者这个(由评论建议):

http://david.tribble.com/text/cdiffs.htm

关于c++ - 为什么 realloc() 在为 C++ 编译时神秘地表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29452720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com