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

标签 c++ c realloc

我有以下函数,我以前在 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/

相关文章:

c - 重新分配两次后出现段错误

c - MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

c - 为什么在 realloc 函数中使用它之前 NULL ing 指针?

c - 函数内动态重新分配 - C

c++ - 错误 C2678 : binary '>' : no operator found which takes a left-hand operand

c - MPI_Allgather 产生不一致的结果

python - 如何在 C/C++ 扩展模块中创建一个在 Python 代码中定义的类的新实例?

c++ - C++/Qt项目的跨平台编译

c++ - 如何在程序中动态初始化一个对象?

c++ - 是否可以从随后被破坏的字符串中本地保存数据而不将其移动到其他地方?