存储数组的子集

时间:2014-04-14 23:42:20

标签: c arrays subset

这个程序是"计算"数组的所有子集 source 。我需要将结果值存储在另一个名为 polje 的2D字段中。如果我只是使用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

2 个答案:

答案 0 :(得分:1)

我认为你只是有一个逻辑错误。你的循环骨架是:

currentSubset = 3;
while ( currentSubset )
{
// ...
    polje[currentSubset][...] = ...;
// ...
    currentSubset--;
}

所以你永远不会写入除前三行之外的任何行。

答案 1 :(得分:1)

tmp是一个只有两位的位掩码,因此内循环应为for ( i = 0; i < 2; i++ )

同样,polje数组的正确索引为polje[currentSubset * 2 + i][0],因为subset中的每个polje占用两个空格,i为0或1。 / p>