c - 存储数组的子集

标签 c arrays subset

此程序正在“计算”数组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]因为每个subsetpolje占用两个空格和 i是 0 或 1。

关于c - 存储数组的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23072269/

相关文章:

c - typedef 结构、循环依赖、前向定义

c++ - 这个返回本地字符数组的遗留代码不是错误的吗?

PHP - 将变量添加到以变量名称作为键的关联数组

r - data.table by = xx 当我返回不匹配时,如何保留长度为 0 的组

r - 查找具有特定值组合的行

java - 在 Java 中创建 NON DISTINCT 值子集的所有多重集

c - ncurses mvaddch() 光标移动可能是一个错误?

c - 在 C 中设置 select() 和 write_fds

从现有(但旧)示例代码创建 DLL

javascript - 如何过滤多维数组