Question

this program is "calculating" all subsets of the array source. I need to store the resulting values in another 2D filed named polje. If I just use the printf("%d %d %d ", source[i][0], source[i][1], source[i][2]); the code works fine but something fails when it is trying to copy everything into the resulting field. I suppose I am dogin something wrong in the indexing of the array 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);
}

The output field should be:

0 3 5
3 4 2
3 4 2
0 0 0
0 3 5 
0 0 0
0 0 0
0 0 0

But instead it is:

0 3 5
3 4 2
3 4 2
0 0 0
*0 0 0* 
0 0 0
0 0 0
0 0 0
Was it helpful?

Solution

tmp is a bit mask with only two bits, so the inner loop should be for ( i = 0; i < 2; i++ ).

Also the correct index into the polje array is polje[currentSubset * 2 + i][0] since each subset in polje takes two spaces and i is either 0 or 1.

OTHER TIPS

I think you just have a logic error. Your loop's skeleton is:

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

So you never write to any rows except the first three.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top