I am new to C and have problems with this code.
int * choose(int * got, int n_chosen, int len, int max_types, int n, int states, int * comb){
int i;
if (n_chosen == len) {
if (!got) return NULL;
for (i = 0; i < len; i++){
comb[len*n + i] = times[got[i]];
printf("%d\n",comb[len*n + i] );
}
++n;
return NULL;
}
for (i = 0; i < max_types; i++) {
if (got) got[n_chosen] = i;
choose(got, n_chosen + 1, len, max_types, n, states, comb);
}
return comb;
}
I basically have the following code:
int num_states = (int) pow(4.0,(double)lab->color_count);
int num = lab->room_count * num_states;
int chosen[4];
int * combinations = malloc(sizeof(int)*num_states*lab->color_count);
choose(chosen, 0, lab->color_count, 4, 0, num_states, combinations);
int a, b;
for(b=0; b < num_states; ++b){
for(a = 0; a < lab->color_count; ++a){
printf("%d\t", combinations[b*lab->color_count + a]);
}
printf("\n");
}
The problem is when I print an array in fuction, I get the correct values, but when printed in basic random values, they print. As I understand it, I passed a pointer, so the values should be the same. Can someone explain to me what is happening and how to fix it?
Additional information: the method is designed to calculate combinations.
EDIT: MVCE
#include <stdio.h>
#include <stdlib.h>
const int times[] = { 0, 1, 2, 3 };
long choose(int * got, int n_chosen, int len, int max_types, int n, int states, int * comb){
int i;
long count = 0;
if (n_chosen == len) {
if (!got) return 1;
for (i = 0; i < len; i++){
comb[len*i + n] = times[got[i]];
printf("%d\n",comb[len*i + n] );
}
return 1;
}
for (i = 0; i < max_types; i++) {
if (got) got[n_chosen] = i;
count += choose(got, n_chosen + 1, len, max_types, n, states, comb);
++n;
}
return count;
}
int main(){
int num_states = 4;
int chosen[4];
int * combinations = malloc(sizeof(int)*num_states*1);
choose(chosen, 0, 1, 4, 0, num_states, combinations);
printf("\n");
int a, b;
for(b=0; b < 1; ++b){
for(a = 0; a < num_states; ++a){
printf("%d\n", combinations[b*2 + a]);
}
}
return 0;
}
I edited MVCE with working code in case anyone needed it.