此程序正在“计算”数组source 的所有子集。我需要将结果值存储在另一个名为 polje 的二维文件中。如果我只是使用 printf("%d %d %d ", source[i][0], source[i][1], source[i][2]);
代码工作正常,但在尝试将所有内容复制到结果字段时出现故障。我想我在数组 polje 的索引中出了点问题。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int f;
int i,j;
int source[2][3] = {{0,3,5},{3,4,2}};
int currentSubset = 3;
int polje[8][3];
for(i=0;i<8;i++){
for(j=0;j<3;j++){
polje[i][j]=0;
}}
int tmp;
while(currentSubset)
{
tmp = currentSubset;
for( i = 0; i<3; i++)
{
if (tmp & 1)
{
printf("%d %d %d ", source[i][0], source[i][1], source[i][2]); //writes out everything I want
polje[currentSubset][0]=source[i][0];
polje[currentSubset][1]=source[i][1];
polje[currentSubset][2]=source[i][2];
}
tmp >>= 1;
}
printf("\n");
currentSubset--;
}
for(i=0;i<8;i++){
for(j=0;j<3;j++){
printf("%d ", polje[i][j]);
}printf("\n");}
return (EXIT_SUCCESS);
}
输出字段应该是:
0 3 5
3 4 2
3 4 2
0 0 0
0 3 5
0 0 0
0 0 0
0 0 0
但它是:
0 3 5
3 4 2
3 4 2
0 0 0
*0 0 0*
0 0 0
0 0 0
0 0 0
最佳答案
tmp
是一个只有两位的位掩码,所以内循环应该是for ( i = 0; i < 2; i++ )
.
还有正确的索引到polje
数组是 polje[currentSubset * 2 + i][0]
因为每个subset
在polje
占用两个空格和 i
是 0 或 1。
关于c - 存储数组的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23072269/