我需要编写一个返回数组数组的函数:
return_array = { {1}, {1,2,3}, {...}, ....};
每个数组都有不同的大小。该功能必须符合以下签名:
int** generate(int n, int** column_sizes)
n
是功能的输入,我用它来创建return-array
。
我知道如何创建return_array
,但是我不明白如何在双指针int** column_sizes
中返回每个数组的大小?
我只会在单个指针int* column_sizes
中返回它们,如下所示:
int** generate(int n, int* column_sizes){
int return_size=some_function(n);
int** returned_array=malloc(return_size*sizeof(int*));
...
column_sizes[0]=c0; // First array size
column_sizes[1]=c1; // Second array size
...
return returned_array;
}
答案 0 :(得分:3)
column_sizes
参数的目的是将返回的双指针的每个子数组中的元素数传递给调用方。
如果要在函数内部分配它,则它必须是双指针。
#include <stdlib.h>
#include <stdio.h>
int** generate(int n, int** column_sizes){
*column_sizes = malloc(n*sizeof(int));
for (int i=0; i<n; i++)
(*column_sizes)[i]=i;
int** return_array=malloc(n*sizeof(*int));
for(int i=0; i<n; i++) {
return_array[i]=malloc((*column_sizes)[i]*sizeof(int));
for(int j=0; j<(*column_sizes)[i]; j++) {
// set the j'th value in the i'th array
return_array[i][j]=i*j;
}
}
return return_array;
}
int main() {
int *column_sizes;
int n=4;
int** arrays= generate(n, &column_sizes);
printf("%i\n", *column_sizes);
for(int i=0; i<n; i++) {
for(int j=0; j<column_sizes[i]; j++) {
printf("%i %i: %i\n",i,j, arrays[i][j]);
}
}
}
答案 1 :(得分:1)
这个问题中有一些未解决的问题,特别是:
尽管如此,我们可以开始回答。看来您需要至少分配 3 个空间:一个用于列大小,一个用于列的指针,一个用于所有实际的int
数据。假设我们将所有列的所有int
数据放在单个数组中,但通过列指针指向数组中的适当位置。另一种方法是分别为每一列的数据分配空间。
在前一种情况下,该函数可以是:
int **generate(int n, int **column_sizes)
{
// Allocate space for columns sizes and assign column sizes.
int NumberOfColumns = /* Some calculation not explained in question. */;
// (size_t would be better than int, but I will use the types in the question.)
int *sizes = malloc(NumberOfColumns * sizeof *sizes);
// Insert code to abort if malloc failed.
*column_sizes = sizes;
int TotalElements = 0;
for (int i = 0; i < NumberOfColumns; ++i)
{
sizes[i] = /* Some calculation to find size of column i. */;
TotalElements += sizes[i];
}
// Allocate space for pointers to columns.
int **returned_array = malloc(NumberOfColumns * sizeof *returned_array);
// Insert code to abort if malloc failed.
// Allocate space for the actual int data.
int *Space = malloc(TotalElements * sizeof *Space);
// Insert code to abort if malloc failed.
// Assign pointers to columns.
returned_array[0] = Space;
for (int i = 1; i < NumberOfColumns; ++i)
returned_array[i] = returned_array[i-1] + sizes[i-1];
// Fill in the actual int data.
for (int i = 0; i < NumberOfColumns; ++i)
for (int j = 0; j < column_sizes[i]; ++j)
returned_array[i][j] = /* Some unexplained calculation. */;
return returned_array;
}
使用此定义,调用者可以通过释放列大小的数组,释放返回的数组中第一个指针指向的空间以及释放返回的数组来释放内存。在另一种实现方式中,如果每个列都是分别分配的,则调用者将不得不释放返回数组中的每个指针。