I would like to create a dynamic array which store permutation sequence, such that
order[0][]={1,2,3}
order[1][]={2,1,3}
order[2][]={2,3,1}
Source Code:
The code will be something like:
#include
int **array;
array = malloc(nrows * sizeof(int *));
if(array == NULL)
{
fprintf(stderr, "out of memory\n");
/*exit or return*/
}
for(i = 0; i < nrows; i++)
{
array[i] = malloc(ncolumns * sizeof(int));
if(array[i] == NULL)
{
fprintf(stderr, "out of memory\n");
/*exit or return*/
}
}
Concept:
array
is a pointer-to-pointer-to-int: at the first level, it points to a block of pointers, one for each row. That first-level pointer is the first one to be allocated; it has nrows
elements, with each element big enough to hold a pointer-to-int
, or int *
. If the allocation is successful then fill in the pointers (all nrows
of them) with a pointer (also obtained from malloc
) to ncolumns
number of ints, the storage for that row of the array.
Pictorial Depiction:
It is simple to grasp if you visualize the situation as:
Taking this into account, the sample code could be rewritten as:
void permute(int num_permute, int num_term, int** order) {
int x, y;
int term[5];
int* ptr = NULL;
for (y=num_term, x=0; y>0; y--, x++) {
term[x] = y;
}
printf("\n");
printf("order%12c", ' ');
for (x=0; x