【问题标题】:How to properly deference a char** pointer passed as an address to functions?如何正确尊重作为地址传递给函数的 char** 指针?
【发布时间】:2021-02-10 00:05:07
【问题描述】:

我正在编写一个使用 char ** 设置多维数组的程序。 然后我将 char ** 的地址传递给另一个函数来使用。

在通过地址将**指针传递给另一个函数后,我如何正确地尊重它们?

错误
c字符串数组
分段错误

int test(char *** strings){
    puts(*strings[0]);
    puts(*strings[1]);
    return 1;
}

int main(void) {

    char arr[][25] =
    { "array of c string",
    "is fun to use",
    "make sure to properly",
    "tell the array size"
    };
    
    
  char ** strings = (char**)malloc(2 * sizeof(char*));
  
  strings[0] = (char*)malloc(25 * sizeof(char));
  strcpy(strings[0], arr[0]);
  
  strings[1] = (char*)malloc(25 * sizeof(char));
  strcpy(strings[1], arr[1]);
  
  test(&strings);

  return 1;
}

*Malloc 被强制转换,以防有人将其插入 C++ 操场

【问题讨论】:

标签: c pointers pass-by-reference c-strings dereference


【解决方案1】:

这行得通:

int test(char *** strings){
    puts((*strings)[0]);
    puts((*strings)[1]);
    return 1;
}

因为[]* 绑定得更紧密,你需要先取消引用。见https://en.cppreference.com/w/c/language/operator_precedence

【讨论】:

    【解决方案2】:

    通过引用将指针strings 传递给函数test 没有太大意义,因为指针本身在函数内没有改变。

    而且返回类型int也没有意义。

    函数至少可以像这样声明和定义

    void test( char ** strings )
    {
        puts( strings[0] );
        puts( strings[1] );
    }
    

    并像这样称呼

    test( strings );
    

    如果你想通过引用传递指针,那么puts 的调用可能看起来像

        puts( ( *strings )[0] );
        puts( ( *strings )[1] );
    

    即首先需要解引用指针,得到main中声明的原始指针strings,然后对得到的原始指针应用下标运算符,

    【讨论】:

      【解决方案3】:

      您可以使用数组表示法,它看起来更好,IMO:

      int test(char ***strings){
          puts(strings[0][0]);
          puts(strings[0][1]);
          return 1;
      }
      

      假设你想改变一个角色:

      strings[0][1][1] = 'z';
      

      这将改变第二个字符串的第二个字符(索引 1),它会是:

      iz fun to use
       ^
      

      如果目标只是访问数据而不是修改它,那么按值传递指针就足够了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-09
        • 2021-09-07
        • 2019-07-26
        • 2013-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-14
        相关资源
        最近更新 更多