将2D数组或指针返回到一个

如果在int 2DRepresentation[mapWidth][mapHeight];创建了一个二维数组int 2DRepresentation[mapWidth][mapHeight]; 在函数内部,返回此函数的最佳方法是什么?

函数如何返回?

是否首选创建指向2d数组的指针并将其传递给函数,在函数内修改它? 如果是这样,指向2D数组的指针看起来如何? 像这样:

int *2DRepresentation[mapWidth][mapHeight];

函数参数如何看起来接受2d数组指针?

您必须返回数组的基址,即Pointer 。 然而,唯一的解决方案是你必须使数组static否则一旦函数超出范围,它将被破坏。 如果您不想使其static ,则应使用dynamic memory allocation

示例伪代码:

  int **array; // array is a pointer-to-pointer-to-int array = malloc(mapHeight * sizeof(int *)); if(array == NULL) { fprintf(stderr, "out of memory\n"); exit or return } for(i = 0; i < mapHeight ; i++) { array[i] = malloc(mapWidth * sizeof(int)); if(array[i] == NULL) { fprintf(stderr, "out of memory\n"); exit or return } } 

这是你可以将它传递给一个名为foo的函数说:

 foo(int **array, int _mapHeight, int _mapWidth) { } 

数组衰减为指针,因此您需要将行和列值作为单独的参数传递。

如果创建了2d数组“int 2DRepresentation [mapWidth] [mapHeight];” 在函数内部,返回此函数的最佳方法是什么?

如果它是在函数内部创建的(假设mapWidth,mapHeight是常量),则不应返回它。 因为它驻留在堆栈上并且在函数返回时超出范围并返回它的引用只是指向垃圾。


是否首选创建指向2d数组的指针并将其传递给函数,在函数内修改它?

是的,你是对的。

函数参数如何看起来接受2d数组指针?

例:

 void foo( int twoDimensionalArray [][3] ) { // Now you can modify the array received. } int main() { int ar[3][3] ; foo(ar) ; // ..... } 

或者你可以在foo动态分配内存并返回它的引用。

 int** foo() { // .... return mallocatedTwoDimensionalArray ; } 

为了使数组在内存中持久化,它需要被声明为static或者应该使用malloccalloc显式分配(每个解决方案都有function含义 – 即下次调用函数时static版本将被覆盖,并且需要在以后显式释放已分配的版本以避免内存泄漏)。

请注意,指针和数组在C中并不相同,因为您在malloc情况下处理动态分配,所以您将使用指针。 使用这些指针引用数组元素在function上与引用数组元素相同,因此一旦创建了数组,您就不会注意到差异。

下面是一个使用单个malloc分配,填充和返回2D数组的示例(为了提高效率,并允许使用单个free进行解除分配):

 int **get2dArray(int rows, int cols) { int **array2d; int i, j, offset; int *gridstart; offset = rows * sizeof(int *); array2d = malloc( offset + rows*cols*sizeof(int) ); /* Demote to char for safe pointer arithmetic */ gridstart = (int *)((char *)array2d + offset); for ( i = 0; i < rows; i++ ) { /* Point to the proper row */ array2d[i] = gridstart + i*cols; /* Populate the array -- your code goes here */ for ( j = 0; j < cols; j++ ) { array2d[i][j] = i*cols + j; } } return array2d; } int main ( int argc, char **argv ) { int **testarray; testarray = get2dArray( 10, 100 ); /* Verify that addressing and population went as planned */ printf( "%d %d %d %d %d %d\n", testarray[0][0], testarray[2][55], testarray[4][98], testarray[5][0], testarray[7][15], testarray[9][99] ); free(testarray); return 0; } 

还有很多其他方法可以做到这一点,但这演示了一个返回2D指针“数组”的函数。

最好在函数外部定义数组并将其传入。

请记住,当用作函数参数时,数组会衰减为指向其第一个元素的指针,因此,在函数内部,它是一个指针,并且没有关于原始大小的信息。 你也需要传递大小。
如果你有一个C99编译器,你可以使用“可变修改参数”(见6.7.5.3):

 int func(int rows, int cols, int data[rows][cols]) { int sum = 0; for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { sum += data[row][col]; } } return sum; } 

并调用它,例如:

 int main(void) { int a[42][100] = {0}; if (func(42, 100, a) == 0) /*ok*/; int b[1000][2] = {0}; if (func(1000, 2, b) == 0) /*ok*/; }