【问题标题】:C++ std::string InputIterator code to C codeC++ std::string InputIterator 代码到 C 代码
【发布时间】:2010-02-12 17:41:41
【问题描述】:

我有一些 C++ 代码,我发现它完全符合我的需要,但是我需要它在 C 中,我不知道如何在 C 中做到这一点,所以我希望有人可以帮助我。

C++ 代码是:

std::string value( (const char *)valueBegin, (const char *)valueEnd );

这是使用 string::string 构造函数:

template<class InputIterator> string (InputIterator begin, InputIterator end);

谁能帮我把它转换成 C 代码?

谢谢!

【问题讨论】:

    标签: c++ c string


    【解决方案1】:
    // Get the number of characters in the range
    size_t length = valueEnd - valueBegin;
    
    // Allocate one more for the C style terminating 0
    char *data = malloc(length + 1);
    
    // Copy just the number of bytes requested
    strncpy(data, valueBegin, length);
    
    // Manually add the C terminating 0
    data[length] = '\0';
    

    【讨论】:

    • malloc()'d 内存也需要为free()'d。
    • 为了不引起警告,strncpy 的第二个参数需要强制转换为:(const char *)
    • @kdbdallas - valueBegin 的类型是什么?我认为它是char *,这意味着您不需要为 strncpy 强制转换。如果不是char *const char *,则可能需要重新计算第一行中的减法。
    【解决方案2】:

    C++ 代码从另一个字符串的子字符串创建新字符串。 C 中的类似功能是strndup

    char *str = strndup(valueBegin, valueEnd - valueBegin);
    // ...
    free(str);
    

    【讨论】:

      【解决方案3】:

      假设指针算法在您的情况下有意义:

      strncpy( value, valueBegin, valueEnd-valueBegin );
      

      【讨论】:

      • 他的示例将value 创建为自动变量,但您假设value 是指向有效内存的指针。
      猜你喜欢
      • 1970-01-01
      • 2019-05-19
      • 2011-12-12
      • 2014-03-21
      • 2014-01-23
      • 1970-01-01
      • 2014-01-19
      • 2011-02-24
      • 1970-01-01
      相关资源
      最近更新 更多