【问题标题】:Double pointer as parameter双指针作为参数
【发布时间】:2016-05-24 14:47:32
【问题描述】:

我有以下原型:

int Split(const char* str, const char* delim,unsigned int& numtokens,char **tokensRes)

最后一个参数用于返回此函数的响应。在函数中我们有以下内容:

.
.
char **tokens =(char**) calloc(tokens_alloc, sizeof(char*));
.
.
.
//at the end of the code
tokensRes = tokens;
.

当函数的返回是char**时直接返回tokens变量的值我得到了正确的答案,但是使用上面的方法返回的函数是空的。如何让这个功能正常工作?

编辑 1: 我的意图是接收一个 char 数组,例如:

array[0] = "ABC"
array[1] = "ABC"
array[2] = "ABC"
array[3] = "ABC"

【问题讨论】:

  • 我使用指向指针的指针,因为我需要一个 char 数组的数组
  • 您要返回字符串还是字符串数组
  • char **tokens = 中删除一个*,因为您正在分配一个指向字符的指针。为什么不使用引用?
  • 由于我们没有看到该功能,因此很难告诉您如何更正它。发一个真实的MCVE

标签: c++ function double-pointer


【解决方案1】:

从以下位置更改原型:

int Split(const char* str, const char* delim,unsigned int& numtokens,char **tokensRes)

收件人:

int Split(const char* str, const char* delim,unsigned int& numtokens,char ** &tokensRes)

代码tokensRes = tokens; 将起作用。了解为什么要详细了解 C++ 和 references

如果您打算从 C 风格的编码转变为 C++ 风格,则有关使用字符串的其他答案也是有效的。编码的便利性会大大提高,并且不用担心内存管理和指针(通常不常见),这些都是由类自动完成的。只要您遵循良好的做法,例如通过引用而不是值传递对象,就不用担心性能下降。

【讨论】:

    【解决方案2】:

    假设您要返回一个字符串数组 (char**),那么您需要将一个指针传递给您可以分配的此类数组。也就是说,您需要传递一个char*** 并将其分配为*tokensRes = tokens

    【讨论】:

    • 你怎么知道这是意图(一个二维数组)?它可能只是一个指向传递的指针的指针,以便函数可以设置指针值。
    【解决方案3】:

    放弃普通的 C 类型并使用 C++ 类型:

    std::vector<std::string> Split(std:;string const& str, std::string const& delim, unsigned int& numtokens);
    

    如果您必须坚持使用 C 接口,则需要使用三重指针进行额外的间接寻址(我假设您要返回一个令牌字符串数组)。

    int Split(const char* str, const char* delim,unsigned int& numtokens,char ***tokensRes)
    
    char** tokens;
    Split("String;String", ";", 2, &tokens);
    

    我真的不喜欢输出参数,我一直想知道为什么有人不在 C++ 中使用std::string

    标记化已在许多库中实现,例如在boost::splitboost::tokenizer。无需重新发明轮子:

    // simple_example_1.cpp
    #include<iostream>
    #include<boost/tokenizer.hpp>
    #include<string>
    
    int main(){
       using namespace std;
       using namespace boost;
       string s = "This is,  a test";
       tokenizer<> tok(s);
       for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){
           cout << *beg << "\n";
       }
    }
    

    simple_example_1 的输出是:

    This
    is
    a
    test
    

    【讨论】:

    • char **&amp;tokensRes
    • @Hurkyl 是的,但是我们有 C++ 并且可以使用 vectorstring。我想给出一个简单的 C 答案。
    猜你喜欢
    • 2012-12-29
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    相关资源
    最近更新 更多