我是C的新手并且在使用此代码时遇到了问题。
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;
}
在主要内容中,我有以下代码:
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("%d\t", combinations[b*lab->color_count + a]);
}
printf("\n");
}
问题是当我在功能中打印数组时,我得到了正确的值,但是当在主要随机值中打印时,会打印出来。据我所知,我传递了一个指针,所以值应该是相同的。有人可以解释一下发生了什么以及如何解决这个问题吗?
额外信息:该方法用于计算组合。
#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;
}