您可能需要考虑动态分配您的数组,以便您可以将指针地址向下传递。
const int m = 5, n = 3;
int i = 0;
int* *arr; //Pointer to an integer pointer (Note can also be int **arr or int** arr)
arr = malloc(sizeof(int*)*(m+1)); //I add one because I am assuming that 'm' does not account for the terminating null character. But if you do not need a terminating null then you can remove this and the perantheses around the 'm'.
for(i = 0; i < m; i++)
{
arr[i] = malloc(sizeof(int*)*(n+1)); //Same as before
}
初始 malloc() 调用为整数数组的数组分配内存,或者换句话说,它分配一个指向一系列其他指针的指针。for 循环将为原始数组的每个元素分配一个“m”大小的整数数组,或者说另一种方式,它将为原始指针地址指向的每个指针地址分配空间。为了简化我的示例,我省略了错误检查,但这里是带有错误检查的相同示例。
const int m = 5, n = 3;
int i = 0;
int* *arr = NULL;
if((arr = malloc(sizeof(int*)*(m+1))) == NULL)
{
perror("ERROR(1): Failed to allocate memory for the initial pointer address ");
return 1;
}
for(i = 0; i < m; i++)
{
if((arr = malloc(sizeof(int*)*(m+1))) == NULL)
{
perror("ERROR(2): Failed to allocate memory for a subsequent pointer address ");
return 2;
}
}
现在您已经动态分配了数组,您只需传递指针地址即可。int* *arr 方式如下。
void fun(const int n, const int m, int* *arr) {}
此外,如果大小是恒定的并且如果您使用以空值结尾的数组,则不必跟踪数组的大小。您只需使用常量整数变量的实际值对数组进行 malloc,然后在迭代抛出数组时检查终止的空字节。
int* *arr = NULL;
if((arr = malloc(sizeof(int*)*6)) == NULL)'m'+1 = 6;
{
perror("ERROR(1): Failed to allocate memory for the initial pointer address ");
return 1;
}
for(i = 0; i < m; i++)
{
if((arr = malloc(sizeof(int*)*4) == NULL)//'n'+1 = 4
{
perror("ERROR(2): Failed to allocate memory for a subsequent pointer address ");
return 2;
}
}
然后,您可以通过以下方式显示整个二维数组。请注意,'\000' 是空字节 (00000000) 的八角形值。
int i, j;
for(i = 0; arr[i] != '\000'; i++)
{
for(j = 0; arr[i][j] != '\000'; j++)
{
printf("%i ", arr[i][j]); //Prints the current element of the current array
}
printf("\n"); //This just ends the line so that each of the arrays is printed on it's own line.
}
当然,上述循环将具有与以下相同的结果。
int i, j;
int m = 5;
int n = 3;
for(i = 0; i < m; i++)
{
for(j = 0; i < n; j++)
{
printf("%i ", arr[i][j]); //Prints the current element of the current array
}
printf("\n"); //This just ends the line so that each of the arrays is printed on it's own line.
}
这意味着,在大多数情况下,不需要跟踪数组的大小,但在某些情况下是必要的。例如,如果您的数组可能包含一个空字节而不是终止空字节。新的空字节会将数组的大小缩短为新空字节的索引。如果您有任何问题或意见,请随时在下面发表评论或给我留言。