问题描述
这是我程序的示例代码.
This is a sample code of my program.
我有一个名为 function
的函数,该函数用于返回整数值和整数数组.我必须将它们作为指针传递(不能更改 function
的签名).所以我写了下面的代码.在这里,我必须将值分配给传递给该函数的双指针.
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.
推荐答案
通过重用概念,我想您已经知道,可以使用指向数组第一个元素的指针,然后使用将指针的地址传递给函数.
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.
这篇关于双指针作为函数的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!