在函数中传递矩阵 (C) [英] Passing a matrix in a function (C)

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

问题描述

我在将矩阵传递给 C 中的函数时遇到问题.我想创建一个函数:

I have an issue passing a matrix to a function in C. There is the function I want to create:

void ins (int *matrix, int row, int column);

但我注意到与向量相比,矩阵给了我一个错误.我怎样才能将我的矩阵传递给一个函数?

but I noticed that in contrast to the vectors, matrix give me an error. How can I pass my matrix to a function so?

编辑 --> 有代码:

EDIT --> there is the code:

// Matrix

#include <stdio.h>
#define SIZE 100

void ins (int *matrix, int row, int column);
void print (int *matrix, int row, int column);

int main ()
{
    int mat[SIZE][SIZE];
    int row, col;

    printf("Input rows: ");
    scanf  ("%d", &row);
    printf("Input columns: ");
    scanf  ("%d", &col);

    printf ("Input data: 
");
    ins(mat, row, col);

    printf ("You entered: ");
    print(mat, row, col);

    return 0;
}

void ins (int *matrix, int row, int column);
{
    int i, j;

    for (i = 0; i < row; i++)
    {
        for (j = 0; j < column; j++)
        {
            printf ("Row %d column %d: ", i+1, j+1);
            scanf  ("%d", &matrix[i][j]);
        }
    }
}

void print (int *matrix, int row, int column)
{
    int i;
    int j;

    for(i=0; i<row; i++)
    {
        for(j=0; j<column; j++)
        {
            printf("%d ", matrix[i][j]);
        }
        printf("
");
    }
}

推荐答案

您需要传递一个指针,该指针的间接层级 (*) 与矩阵的维数一样多.

You need to pass a pointer with as much levels of indirection (*) as the number of dimensions of your matrix.

例如,如果您的矩阵是二维矩阵(例如 10 x 100),则:

For example, if your matrix is 2D (e.g. 10 by 100), then:

void ins (int **matrix, int row, int column);

如果你有一个固定的维度(比如 100),你也可以这样做:

If you have a fixed dimension (e.g. 100), you can also do:

void ins (int (*matrix)[100], int row, int column);

或者你的情况:

void ins (int (*matrix)[SIZE], int row, int column);

如果你的两个维度都是固定的:

If both your dimensions are fixed:

void ins (int matrix[10][100], int row, int column);

或者你的情况:

void ins (int matrix[SIZE][SIZE], int row, int column);

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

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