gpt4 book ai didi

c - 将二维数组拆分为 C 中较小二维数组的数组

转载 作者:太空狗 更新时间:2023-10-29 15:24:29 26 4
gpt4 key购买 nike

给定:

1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8

我想将二维数组(struct MATRIX)拆分为一个 struct MATRIX 数组给定一个 block 大小的 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、行数、列数、填充类型)和 mallocs。

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];

最佳答案

我不明白你为什么要用 ChunkSizer 的乘法运算(无论如何都未初始化),我建议简化代码(规则经验:如果它看起来很乱,那就太复杂了)。您只需要一个 3 维数组来存储 block 数组,以及模运算和整数除法以插入到适当 block 的适当列中:

/* the variable-sized dimension of the `chunks' argument is w / chsz elements big
* (it's the number of chunks)
*/
void split(int h, int w, int mat[h][w], int chsz, int chunks[][h][chsz])
{
/* go through each row */
for (int i = 0; i < h; i++) {
/* and in each row, go through each column */
for (int j = 0; j < w; j++) {
/* and for each column, find which chunk it goes in
* (that's j / chsz), and put it into the proper row
* (which is j % chsz)
*/
chunks[j / chsz][i][j % chsz] = mat[i][j];
}
}
}

演示,一个。 k.一种。如何调用它:

int main(int agrc, char *argv[])
{
const size_t w = 8;
const size_t h = 3;
const size_t c = 2;

int mat[h][w] = {
{ 1, 2, 3, 4, 5, 6, 7, 8 },
{ 1, 2, 3, 4, 5, 6, 7, 8 },
{ 1, 2, 3, 4, 5, 6, 7, 8 }
};

int chunks[w / c][h][c];

split(h, w, mat, c, chunks);

for (int i = 0; i < w / c; i++) {
for (int j = 0; j < h; j++) {
for (int k = 0; k < c; k++) {
printf("%3d ", chunks[i][j][k]);
}
printf("\n");
}
printf("\n\n");
}

return 0;
}

关于c - 将二维数组拆分为 C 中较小二维数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16528801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com