将1D数组转换为矩阵

时间:2018-06-11 15:38:36

标签: c arrays matrix binary

我有一个具有以下值的单维数组:

 10010011

我想按照以下顺序将此单维数组转换为2X4矩阵:

 1001
 0011

我尝试的代码如下:

#include <stdio.h>
#include <stdlib.h>
#define rows_Matrix 2
#define cols_Matrix 4

void print2DArray(unsigned **arr, int m, int q);

int main()
{
   int k = 0; 
   unsigned Array[8] = { 1, 0, 0, 1, 0, 0, 1,  1};

   //Allocation of Memory. 
   unsigned **Matrix = (unsigned **)malloc(sizeof(unsigned *)*rows_Matrix); //Rows

   for (int i = 0; i < rows_Matrix; i++) //Rows
   {
       Matrix[i] = (unsigned *)malloc(sizeof(unsigned ) * cols_Matrix); //Columns 
   }

   do
   {
       for (int i = 0; i < rows_Matrix; i++)
       {
           for (int j = 0; j < cols_Matrix; j++)
           {        
               Matrix[i][j] = Array[k];
           }
       }

      k++;

    } while (k < 8);

    print2DArray(Matrix, 2, 4);

    return 0;

}

   void print2DArray(unsigned **arr, int m, int q)
   {
        for (int i = 0; i < m; i++) //Rows
        {
            for (int j = 0; j < q; j++)//Columns
            {
               printf("%d\t", arr[i][j]);
            }
               printf("\n");
        }
       printf("\n");
   } 

但我得到的答案是:

 1       1       1       1
 1       1       1       1

我想知道为什么没有正确分配值。这似乎是我这样做的方式我只是复制单维数组的第一个元素。

1 个答案:

答案 0 :(得分:0)

你在错误的地方增加了。所以Array [k]表示相同的元素。

#include <stdio.h>
#include <stdlib.h>
#define rows_Matrix 2
#define cols_Matrix 4

void print2DArray(unsigned **arr, int m, int q);

int main()
{
   int k = 0;
   unsigned Array[8] = { 1, 0, 0, 1, 0, 0, 1,  1};

   //Allocation of Memory.
   unsigned **Matrix = (unsigned **)malloc(sizeof(unsigned *)*rows_Matrix); //Rows

   for (int i = 0; i < rows_Matrix; i++) //Rows
   {
       Matrix[i] = (unsigned *)malloc(sizeof(unsigned ) * cols_Matrix); //Columns
   }

   do
   {
       for (int i = 0; i < rows_Matrix; i++)
       {
           for (int j = 0; j < cols_Matrix; j++)
           {

               Matrix[i][j] = Array[k]; 
               k++; //updated
           }

       }


    } while (k < 8);

    print2DArray(Matrix, 2, 4);

    return 0;

}

   void print2DArray(unsigned **arr, int m, int q)
   {
        for (int i = 0; i < m; i++) //Rows
        {
            for (int j = 0; j < q; j++)//Columns
            {
               printf("%d\t", arr[i][j]);
            }
               printf("\n");
        }
       printf("\n");
   }