如何使用malloc定义2D数组并将其传递给函数 [英] how to define a 2d array using malloc and pass it to a function
问题描述
我想将我使用malloc定义的2d数组传递给函数.首先,我使用博客文章中的代码定义数组.
I want to pass a 2d array i defined using malloc to a function. First i define the array using code from a blog post.
int** Make2DIntArray(int arraySizeX, int arraySizeY) {
int** theArray;
theArray = (int**) malloc(arraySizeX*sizeof(int*));
for (int i = 0; i < arraySizeX; i++)
theArray[i] = (int*) malloc(arraySizeY*sizeof(int));
return theArray;
}
int main(){
int** myArray = Make2DIntArray(nx, ny);
}
然后我可以将其用作myArray [i] [j].之后,我想将此数组传递给一个函数.我试图像这样传递它:
I can then use it as myArray[i][j]. After that,i want to pass this array to a function.I tried to pass it like this:
function(myArray); //function call
//function
void function(int myArray[][]){
//function code goes here
}
但是这是错误的.问题在于数组的大小每次都不同.我还尝试为数组的列定义最大大小并像这样使用它:
but this is wrong.The problem is that the size of the array is different every time.I also tried to define a maximum size for the columns of the array and use it like this:
#define COLUMNMAX 100
function(myArray); //function call
//function
void function(int myArray[][COLUMNMAX]){
//function code goes here
}
但是我得到了错误:
形式参数1的类型不完整.如何传递?
type of formal parameter 1 is incomplete.How can i pass it?
推荐答案
该参数是 int **
您不必强制转换malloc的返回值,只需检查它是否不为NULL
And you don't have to cast the return of malloc, just check if it's not NULL
但是由于您使用了malloc,所以当您不再需要它时就不要使用free
But since you use malloc don't use free when you don't need it anymore
这篇关于如何使用malloc定义2D数组并将其传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!