将矩阵作为参数传递 [英] Pass matrix as argument

查看:158
本文介绍了将矩阵作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递两个矩阵作为参数.这些矩阵的大小不同,我不知道该怎么做:

I want to pass two matrices as argument. These matrices have different size and i don't understand how i have to do this work:

#include <stdio.h>
#include <stdlib.h>


void f(int m[3][], int n);

int main()
{
  int A[3][3]={{1,2,3},{4,5, 6},{7,8,9}};
  int B[3][2]={{1,2},{3, 4}, {5, 6}};

  f(A, 3);
  f(B, 2);

  return 0;
}

 void f(int m[3][], int n)
 {
    int i,j;
    for(i=0;i<3;i++)
    {
      for(j=0;j<n;j++)
       printf("%5d", m[i][j]);
    }
    return;
 }

我该怎么做?

推荐答案

我知道做到这一点的唯一安全方法是在参数中包含矩阵维数,或制作某种矩阵结构

The only safe way that I know of to do this is to include the matrix dimensions in the parameters, or make some kind of matrix struct

选项A)尺寸作为参数

void f(int **m, int w, int h )
{
    int i,j;
    for(i=0;i<w;i++)
    {
      for(j=0;j<h;j++)
         printf("%5d", m[i][j]);
    }
    return;
}

选项B)使用结构

typedef struct Matrix
{
    int w, h;
    int** m;
} Matrix;

void f ( Matrix *m )
{
    for ( int i = 0; i < m->w; ++i )
    {
        for ( int j = 0; j < m->h; ++j )
        {
            printf(%5d", m->m[i][j]);
        }
    }
}

这篇关于将矩阵作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆