There are some unresolved issues in the question, notably:
- How are the column sizes determined?
- How will the caller free the allocated memory?
Nonetheless, we can start answering. It looks like you need to allocate at least three spaces: One for the column sizes, one for the pointers to the columns, and one for all the actual int
data. This supposes we put all the int
data for all the columns in a single array but point into appropriate places in the array through the column pointers. An alternative is to allocate space for each column’s data separately.
In the former case, the function could be:
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;
}
With this definition, the caller could free the memory by freeing the array of column sizes, freeing the space pointed to by the first pointer in the returned array, and freeing the returned array. If, in an alternative implementation, each column is allocated separately, the caller would have to free each pointer in the returned array.