c++ - strdup 指针版本需要一个临时指针

标签 c++ pointers c-strings strdup

我正在实现一个 strdup 函数作为练习。

char* strdupPtr(const char* str) {
    const size_t sz{strlen(str)+1};
    char *save, *temp;
    save = temp = (char*)malloc(sz);
    while((*temp++ = *str++));  // compiler warning with only 1 set of   parenthesis
    return save;
}

在几次失败后,我发现在“保存”(wiki reference) 时它可以正常工作。返回指针,但在返回“temp”时不返回。为什么在处理指针时需要返回 save 而不是直接返回 temp(下标数组版本可以不使用 save)?

最佳答案

在函数指针 temp 中递增。

while((*temp++ = *str++));  

所以如果返回temp那么它不会包含分配内存的起始地址。

例如,这些用例将无效。

char *p = strdup( "Hello World" );

puts( p );

free( p );

考虑到在 C++ 中最好使用 operator new。 例如

char * strdupPtr( const char *s ) 
{
    char *p = new char[std::strlen( s ) + 1];

    std::strcpy( p, s );

    return p;
}

或者你甚至可以写

char * strdupPtr( const char *s ) 
{
    char *p = new char[std::strlen( s ) + 1];

    return std::strcpy( p, s );
}

关于c++ - strdup 指针版本需要一个临时指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31360426/

相关文章:

c++ - 我可以将 main() 中的代码替换为全局对象的构造函数吗?

c++ - 当强制转换的指针具有增量运算符时会发生什么?

C 中带指针的自定义 concat 函数

c - 如果在给指针的内存位置赋值后指针递增,会发生什么情况?

c - 字符串末尾的空字符 '\0'

c++ - 使用库时的标准 - 使用库的数据类型 VS 创建我自己的类型?

c++ - 为什么即使我使用指针,我的代码也不交换变量的值?

c++ - CreateBuffer 抛出 "Access violation reading location"

c - 如何从 char 数组转换/复制以便我可以将它存储在 char 指针数组中?

c++ - 在c++中添加两个c字符串