Reputation: 69
so i have a matrix struct and i have to fill with permutations ranging from 0~nr_vals in N columns. I finished the permutation part but i cannot figure out the pointers with the array. Any Help would be appreciated. There is a printing function that i call and all i does it prints and thats it. Its supposed to print the permutations(DONE) after allocating them to the matrix. what am i doing wrong and also how do i free the matrix?
printing function:
void print_2D(matrix_ptr mat);
struct matrix_2D_struct {
int** data_arr;
int rows;
int cols;
};
typedef struct matrix_2D_struct * matrix_ptr;
matrix_ptr perm_rec_2(int N, int nr_vals) {
struct matrix_2D_struct *matrix = malloc(sizeof *matrix);
int j = 0;
int i = 0;
prem_rec_helpTwoForMatrix (N, nr_vals, i, matrix->data_arr, j);
return NULL;
}
void prem_rec_helpTwoForMatrix(int N, int nr_vals, int i, int **a[], int j)
{
i = N - 1;
while(a[i][j] < nr_vals){
a[i][j]++;
}
while(i >= 0 && a[i][j] == nr_vals){
i--;
}
if(i < 0)
{
return;
}
a[i][j]++;
while(++i < N)
{
a[i] = 0;
}
prem_rec_helpTwoForMatrix(N, nr_vals, i, **a, j);
}
Upvotes: 1
Views: 78
Reputation: 31669
This is a partial answer:
After allocating matrix
, you have to allocate matrix->data_arr
.
Assuming that the array is N
xN
large:
struct matrix_2D_struct *matrix = malloc(sizeof *matrix);
if (N < 1)
{
printf("error!\n");
return ...
}
matrix->data_arr = malloc(N*sizeof(int*));
int i, j;
for (i = 0; i < N; i++)
matrix->data_arr[i] = malloc(N*sizeof(int));
Initialization (as suggested in comment)
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
matrix->data_arr[i][j] = 0;
Now you can test to see if it works:
matrix->data_arr[2][0] = 20;
matrix->data_arr[0][4] = 4;
printf("%d\n", matrix->data_arr[2][0]);
printf("%d\n", matrix->data_arr[0][4]);
When you no longer need the data, you can free it (the data is freed automatically when you exit the program)
for (i = 0; i < N; i++)
free(matrix->data_arr[i]);
free(matrix->data_arr);
free(matrix);
Upvotes: 1