# switch from 2d array to 1d array

This is a discussion on switch from 2d array to 1d array within the C Programming forums, part of the General Programming Boards category; i have a 2d array...W[9][9] and i want to put it a 1d array w_in1d[81] but it gives me the ...

1. ## switch from 2d array to 1d array

i have a 2d array...W[9][9] and i want to put it a 1d array w_in1d[81]
but it gives me the wrong values

Code:
/*initialize W_in1d matrix*/
for(i = 0; i < 81; i++){
W_in2d[i]=0.0;
}

for(k = 0; k < 81; k++){
for (i = 0; i < 9; i++)
for (j = 0; j < 9; j++)
W_in1d[k]=W[i][j];
}

for (i = 0; i < 81; i++) {
printf("%6.4lf ", W_in1d[i]);
}

2. You've got too many loops.
Code:
for(k = 0; k < 81; k++){
for (i = 0; i < 9; i++)
for (j = 0; j < 9; j++)
W_in1d[k]=W[i][j];
}

3. well dont you need 3 loops?

4. Aren't you trying to do this?
Code:
#include <stdio.h>
int main(void)
{
float b[9][9], a[(sizeof b / sizeof *b) * (sizeof *b / sizeof **b)];
size_t i, j, k = 0;

for ( i = 0; i < sizeof b / sizeof *b; i++ )
{
for ( j = 0; j < sizeof *b / sizeof **b; j++ )
{
b[i][j] = k++;
}
}

k = 0;
for ( i = 0; i < sizeof b / sizeof *b; i++ )
{
for ( j = 0; j < sizeof *b / sizeof **b; j++ )
{
a[k++] = b[i][j];
}
}

for ( i = 0; i < sizeof a / sizeof *a; i++ )
{
printf("%6.4f ", a[i]);
}
return 0;
}

5. no i allready have values in the 2d array and i want to transfer them to an empty 1d array

6. Uh, that's what this is doing.
Code:
k = 0;
for ( i = 0; i < sizeof b / sizeof *b; i++ )
{
for ( j = 0; j < sizeof *b / sizeof **b; j++ )
{
a[k++] = b[i][j];
}
}
Or do you see a being assigned values somewhere that I don't?

7. it says
warning: comparison between signed and unsigned

8. and it changes the values in my array

9. I don't suppose you could do what I did and post your code that actually demonstrates the issue?

Originally Posted by sass208
it says
warning: comparison between signed and unsigned
Oh, wait. You didn't copy and paste all of my code, you only did it part way, right?

10. OK great!!!
ya i had put the first part of what u posted...i took it off and now it works !!! yay
but it still has that warning

warning: comparison between signed and unsigned

11. ok i fixed it up
it runs perfectly!
thank you soooooooooo much!

12. Uh, where? With the i,j,k? I don't suppose you used the size_t that I did, and instead used int. That would be a signed/unsigned issue.

13. hi man,

Hey Im new to this programming language, so dont mind if I say something wrong ok.

I think you can go with this code:
Code:
k=0;
for (i=0;i<9;i++)
{
for (j=0;j<9;j++)
{
w_in1d[k]=w_in2d[i][j];
k++;
}
}
it will copy all your 2d elements to 1d