我有两个在运行时创建的整数数组(大小取决于程序输入)。在某些时候,我需要用一个数组的内容来更新数组的内容,并进行一些计算。是否可以将指针传递给数组并将其作为函数参数传递?
首先,我想过将这些数组作为参数传递给一个函数,因为我没有找到一种方法来在C中返回函数(不要认为这是可能的)。意识到这是一个坏主意,因为参数不能真正修改,因为它们被复制到堆栈上,我改用数组指针来代替。
虽然功能仍然是空的,这是我的代码:
1日起飞(代码编译,没有错误):
// Elements is just to be able to iterate through their contents (same for both):
void do_stuff(int first[], int second[], int elements) {}
// Call to the function:
do_stuff(first, second, elements);
2日起飞,企图转换为指针能够修改阵列到位:
void do_stuff(int *first[], int *second[], int elements) {}
// Call to the function:
do_stuff(&first, &second, elements);
这个代码导致一些应有的编译时错误,因为很明显我认为是指向数组是指针数组。
3取,我觉得这是正确的语法:
void do_stuff(int (*first)[], int (*second)[], int elements) {}
// Call to the function:
do_stuff(&first, &second, elements);
不过此代码生成试图访问阵列(例如*first[0]
)的元素时,编译时错误:
error: invalid use of array with unspecified bounds
所以我的问题是关于使用数组指针作为函数的参数的可能性,有可能吗?如果是这样,那该怎么办?
无论如何,如果您想在执行包含第二个内容的计算后更新第一个数组的更好方法,请对其进行评论。
当您将一个数组作为函数参数传递时,实际上您将一个指针传递给第一个元素,因此您可以使用该指针从函数修改数组。 –