二维数组、动态内存

#include<stdio.h>
typedef int(*TYPE)[2];
TYPE matmul(int(*m1)[3], int(*m2)[2])
{
  int(*b)[2] = (int(*)[2])malloc(2 * 2 * sizeof(int));
  for (int i = 0; i < 2; i++)
  {
    for (int j = 0; j < 2; j++)
      b[i][j] = 0;
  }
  int i_m1, j_m1, i_m2, j_m2;
  for (i_m1 = 0; i_m1 < 2; i_m1++)  // 先是m1的行
  {

    for (j_m2 = 0, i_m2 = 0; j_m2 < 2; j_m2++)  // 输出的行由m2的列决定
    {
      for (i_m2=j_m1 = 0; j_m1 < 3; j_m1++, i_m2++)  // m1列递增,同时m2行递增
      {
        b[i_m1][j_m2] += m1[i_m1][j_m1] * m2[i_m2][j_m2];
      }
    }
  }
  return b;
}

int main(void)
{
  int m1[2][3] = { {1,2,3},{4,5,6} };
  int m2[3][2] = { {1,2},{2,3},{3,4} };

  int(*mm)[2] = matmul(m1, m2);

  for (int i = 0; i < 2; ++i)
  {
    for (int j = 0; j < 2;++j)
      printf("%d ", mm[i][j]);
    printf("\n");
  }

  free(mm);
  return 0;
}

 

说点什么

avatar

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

  Subscribe  
提醒