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}
let say order[m][n], m = number of permutation, n = number of term, m and n are identified in real-time.
I did the below, and found that the pointer address is overlapping, resulting in incorrect value storage. How can do it correctly using dynamic array via double pointer?
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;
}
Result: order[0][1] and order[1][0] point to same address... and so do others. With rows as the major axis and columns the minor:
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
