2012-08-29 39 views
0

我有两个在运行时创建的整数数组(大小取决于程序输入)。在某些时候,我需要用一个数组的内容来更新数组的内容,并进行一些计算。是否可以将指针传递给数组并将其作为函数参数传递?

首先,我想过将这些数组作为参数传递给一个函数,因为我没有找到一种方法来在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 

所以我的问题是关于使用数组指针作为函数的参数的可能性,有可能吗?如果是这样,那该怎么办?

无论如何,如果您想在执行包含第二个内容的计算后更新第一个数组的更好方法,请对其进行评论。

+0

当您将一个数组作为函数参数传递时,实际上您将一个指针传递给第一个元素,因此您可以使用该指针从函数修改数组。 –

回答

2

数组衰减为指向为数组分配的数据的指针。传递给函数时,数组不会被复制到堆栈。因此,你不需要传递一个指向数组的指针。所以,下面应该可以正常工作。

// 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); 

你的错误在您的第二次尝试的原因是因为int *first[](以及其他类似的)是类型数组指针的实际为int

第三错误的原因是因为*first[N]实际上是*(first[N]),不能轻松完成。数组访问实际上是指针算术的正面,*(first + sizeof first[0] * N);但是,这里有一个不完整的元素类型 - 您需要指定数组的大小,否则sizeof first[0]未知。

1

你的第一次尝试是正确的。当在C中传递一个数组作为参数时,实际上会传递一个指向第一个元素的指针,而不是数组的副本。所以,你可以写任何

void do_stuff(int first[], int second[], int elements) {} 

喜欢你了,或者

void do_stuff(int *first, int *second, int elements) {} 
0

在C数组自动衰减到指针数据,所以,你可以只通过阵列和它们的长度,并得到想要的结果。

我的建议是这样的:

void dostuff(int *first, int firstlen, int *second, int secondlen, int elements) 

函数调用应该是:

do_stuff(first, firstlen, second, secondlen, elements); 

我不是很清楚你的问题,你为什么需要elements。但是,您必须传递数组长度,因为数组在传递给函数时自动衰减为指针,但在被调用的函数中,无法确定它们的大小。

+0

'elements'指定了数组的长度,我意识到'length'更清晰了;谢谢。 –