Double pointer as an array to a function [duplicate]

烈酒焚心 提交于 2021-02-11 07:54:29

问题


This is a sample code of my program.

I have a function named function which is used to return an integer value and an integer array. I have to pass them as pointers (The signature of function cannot be changed). So I wrote the below code. Here I have to assign the values to the double pointer passed to the 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;
}

But the above code is not working.


回答1:


By reusing concepts I suppose you already know, you might use a pointer to the first element of the array and then pass the pointer's address to the function.

In that way you would have a double pointer to an unsigned int which is the first element of the array:

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;
 }

As a sidenote:

If you could change the signature this would have made more sense:

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;
 }

The reason the above works is because when you pass an array into a function (directly or with an explicit pointer to that array) it essentially becomes a pointer. This is called array decaying.




回答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:


To assign to an array that is passed by pointer, first dereference it, then assign the value.

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


来源:https://stackoverflow.com/questions/21725274/double-pointer-as-an-array-to-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!