给定:
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
我希望将二维数组(结构体MATRIX)拆分为一组结构体MATRIX的数组,给定一个块大小CS: 假设CS为2, 答案将是
Seg[0]:
1 2
1 2
1 2
Seg[1]:
3 4
3 4
3 4
....
Seg[3]:
7 8
7 8
7 8
这是我的矩阵结构体:
typedef struct MATRIX {
int nrow;
int ncol;
int **element;
} MATRIX;
以下是将它们分开的函数:
void SegmentMatrix(MATRIX input,MATRIX* segs,int Chunksize, int p) {
int i,j,r;
//Allocate segs
for (i = 0; i<p;i++)
{
CreateMatrix(&(segs[i]),input.nrow ,Chunksize,0);
}
//Now Copy the elements from input to the segs
//where seg0 takes from 0 to cs cols of a, and all their rows, and seg1 takes from cs to 2cs ...
printf("Stats:\n\t P: %d\t CS: %d\n",p,Chunksize);
for (r = 0; r<p; r++) {
for (i = 0; i<input.nrow;i++) {
for (j = r*Chunksize; j<r*Chunksize+Chunksize-1; j++) {
//I tried (&(segs[r]))->element... Doesn't work, produces wrong data
segs[r].element[i][j] = input.element[i][j];
}
}
PRINTM(segs[r]);
}
}
请注意,PRINTM基本上打印矩阵,它通过检查segs[r].nrow和ncol来知道限制,而CreateMatrix需要以下输入(&matrix、行数、列数、填充类型),并从内部进行malloc操作。
filltype:
0- generates zeroth matrix
1- generates identity
else A[i][j] = j; for simplicity
问题在于,如果我打印矩阵Segs [i],它们都会使用CreateMatrix给定的默认值下降,而不是新添加的值。
澄清: 好的,如果你们检查一下SegmentMatrix函数中的最后一个PRINTM,它的输出就好像for循环没有发生过一样,也就是说,我可以删除for循环,得到相同的输出结果... 我在SegmentMatrix中这一行做错了什么?
Segs[r].element[i][j] = input.element[i][j];