我想创建一个存储排列序列的动态数组,这样
order[0][]={1,2,3}
order[1][]={2,1,3}
order[2][]={2,3,1}
假设 order[m][n],m = 排列数,n = 项数,m 和 n 是实时识别的。
我做了下面的操作,发现指针地址重叠,导致值存储不正确。如何通过双指针使用动态数组正确地做到这一点?
void permute(int num_permute, int num_term, int** order) {
int x, y;
int term[5];
/* debug only */
for(y=num_term, x=0; y>0; y--, x++){
term[x] = y;
}
fprintf(stderr, "\n");
printf("order%12c", ' ');
for (x=0; x<num_permute; ++x) {
printf(" %-11d", x);
}
printf("\n");
for(y=0; y<num_permute; y++){
printf("%-5d%12p", y, (order+y));
memcpy(&(order[y]), term, sizeof(term));
for (x=0; x<num_term; x++)
printf(" %12p", order+y+x);
printf("\n");
}
}
int main(){
int y, z;
int** x;
x = (int*) malloc(5*5*sizeof(int*));
permute(5, 5, x);
printf("\n");
printf("x ");
for(z=0; z<5; z++){
printf(" %2d ", z);
}
printf("\n");
for(y=0; y<5; y++){
printf("%-4d", y);
for(z=0; z<5; z++){
printf(" %2d ", *(x+y+z));
}
printf("\n");
}
free(x);
return 0;
}
结果:order[0][1] 和 order[1][0] 指向相同的地址...其他也是如此。以行为长轴,以列为次轴:
order 0 1 2 3 4
0 0x100100080 0x100100080 0x100100084 0x100100088 0x10010008c 0x100100090
1 0x100100084 0x100100084 0x100100088 0x10010008c 0x100100090 0x100100094
2 0x100100088 0x100100088 0x10010008c 0x100100090 0x100100094 0x100100098
3 0x10010008c 0x10010008c 0x100100090 0x100100094 0x100100098 0x10010009c
4 0x100100090 0x100100090 0x100100094 0x100100098 0x10010009c 0x1001000a0
x 0 1 2 3 4
0 5 5 5 5 5
1 5 5 5 5 4
2 5 5 5 4 3
3 5 5 4 3 2
4 5 4 3 2 1