在C中将动态分配的数组作为参数传递
所以...我的主服务器上有一个动态分配的数组:
So... I have a dynamically allocated array on my main:
int main()
{
int *array;
int len;
array = (int *) malloc(len * sizeof(int));
...
return EXIT_SUCCESS;
}
我还想构建一个函数来对该动态分配的数组进行处理. 到目前为止,我的功能是:
I also wanna build a function that does something with this dynamically allocated array. So far my function is:
void myFunction(int array[], ...)
{
array[position] = value;
}
如果我声明为:
void myFunction(int *array, ...);
我仍然可以这样做:
array[position] = value;
否则我将不得不做:
*array[position] = value;
...?
此外,如果我正在使用动态分配的矩阵,那是声明函数原型的正确方法:
Also, if I am working with a dynamically allocated matrix, which one is the correct way to declare the function prototype:
void myFunction(int matrix[][], ...);
或
void myFunction(int **matrix, ...);
...?
如果我声明为:
If I declare it as:
void myFunction(int *array, ...);
我仍然可以这样做:
array[position] = value;
是的-这是合法语法.
此外,如果我使用的是动态分配的矩阵,那么哪个 正确声明函数原型:
Also, if I am working with a dynamically allocated matrix, which one is correct to declare the function prototype:
void myFunction(int matrix[][], ...);
或
void myFunction(int **matrix, ...);
...?
如果要使用多个维度,则必须在函数声明中声明除第一个维度以外的所有维度的大小,如下所示:
If you're working with more than one dimension, you'll have to declare the size of all but the first dimension in the function declaration, like so:
void myFunction(int matrix[][100], ...);
此语法不会执行您认为的操作:
This syntax won't do what you think it does:
void myFunction(int **matrix, ...);
matrix[i][j] = ...
这将声明一个名为matrix
的参数,该参数是一个指向int的指针.尝试使用matrix[i][j]
取消引用可能会导致分段错误.
This declares a parameter named matrix
that is a pointer to a pointer to int; attempting to dereference using matrix[i][j]
will likely cause a segmentation fault.
这是在C中使用多维数组的众多困难之一.
This is one of the many difficulties of working with a multi-dimensional array in C.
以下是解决此主题的有用的SO问题: 定义矩阵并将其传递到C中的功能
Here is a helpful SO question addressing this topic: Define a matrix and pass it to a function in C