【问题标题】:Double pointer as an array to a function [duplicate]双指针作为指向函数的数组[重复]
【发布时间】:2014-02-12 10:32:06
【问题描述】:

这是我的程序的示例代码。

我有一个名为function 的函数,它用于返回一个整数值和一个整数数组。我必须将它们作为指针传递(function 的签名不能更改)。所以我写了下面的代码。在这里,我必须将值分配给传递给函数的双指针。

void function(unsigned int* count, unsigned int ** array)
{
  for(unsigned int i = 0; i<4;i++)
  {
    //array[i] = (unsigned int*)i*10;
  }
  *count = 4;
}

int main()
{

  unsigned int count;
  unsigned int array2[4];
  function(&count, (unsigned int**)&array2);

  return 0;
}

但是上面的代码不起作用。

【问题讨论】:

  • 您的程序不会产生任何可观察到的输出。它怎么能证明你的问题?在某些时候,您必须对其进行测试以查看它是否有效。
  • 我的主要需要是用指定的值填充函数'function'中的数组'array2'。我在VS中调试代码检查它是否正常工作。

标签: c arrays pointers


【解决方案1】:

通过重用我想你已经知道的概念,你可以使用指向数组第一个元素的指针,然后将指针的地址传递给函数。。 p>

这样你就会有一个指向数组第一个元素的无符号整数的双指针:

void function(unsigned int* count, unsigned int ** array)
{
  for(unsigned int i = 0; i<4;i++)
  {
    (*array)[i] = i*10; // WATCH OUT for the precedence! [] has higher precedence!
  }
  *count = 4;
}

int main(int argc, char* argv[])
{

  unsigned int count;
  unsigned int array2[4];
  unsigned int *pointer_to_array = &array2[0];
  function(&count, (unsigned int**)&pointer_to_array);

  return 0;
 }

作为旁注:

如果您可以更改签名,这将更有意义:

void function(unsigned int* count, unsigned int * array)
{
  for(unsigned int i = 0; i<4;i++)
  {
    array[i] = i*10;
  }
  *count = 4;
}

int main(int argc, char* argv[])
{

  unsigned int count;
  unsigned int array2[4];
  function(&count, array2);

  return 0;
 }

上述工作的原因是,当您将数组传递给函数(直接或使用指向该数组的显式指针)时,它实际上变成了一个指针。这称为数组衰减

【讨论】:

  • 他显然不允许更改函数签名(详情请参阅问题)- 可能是作业?
  • 谢谢保罗,我错过了!
  • @Paul: 你的评论好像很有趣,谢谢支持
【解决方案2】:
void function(unsigned int* count, unsigned int ** array){
    for(unsigned int i = 0; i<4;i++){
        (*array)[i] = i*10;
    }
    *count = 4;
}

int main(){
    unsigned int count;
    unsigned int array2[4];
    unsigned int *p = &array2[0];
    function(&count, &p);
    return 0;
}

【讨论】:

    【解决方案3】:

    要分配给通过指针传递的数组,首先取消引用它,然后分配值。

    void function(unsigned int* count, unsigned int ** array)
    {
      for(unsigned int i = 0; i<4;i++)
      {
        (*array)[i] = i*10;
      }
      *count = 4;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-01
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多