定义一个矩阵,并把它传递给C中的函数 [英] Define a matrix and pass it to a function in C

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

问题描述

我想创建一个程序中,我可以通过一个矩阵来使用指针的函数。
我初始化,并在无效的主要(),然后我试图向他们传递给无效添加功能扫描2矩阵。我想我在声明的语法脚麻和调用功能。我分配指针我的基质的基地址。 (对于如:为int * x = a [0] [0],* Y = B [0] [0] )。什么是正确的声明?如何指定的尺寸?

I want to create a program in which I can pass a matrix to a function using pointers. I initialized and scanned 2 matrices in the void main() and then I tried to pass them to a void add function. I think I am going wrong in the syntax of declaration and calling of the function. I assigned a pointer to the base address of my matrix. (for eg: int *x=a[0][0], *y=b[0][0]). What is the right declaration? How can I specify the dimensions?

推荐答案

这样的事情应该做的伎俩。

Something like this should do the trick.

#define COLS 3
#define ROWS 2

/* Store sum of matrix a and b in a */
void add(int a[][COLS], int b[][COLS])
{
    int i, j;

    for (i = 0; i < ROWS; i++)
        for (j = 0; j < COLS; j++)
            a[i][j] += b[i][j];
}

int main()
{
    int a[ROWS][COLS] = { { 5, 10, 5} , { 6, 4, 2 } };
    int b[ROWS][COLS] = { { 2, 3, 4} , { 10, 11, 12 } };

    add(a, b);

    return 0;
}

修改:除非你想在运行时指定的尺寸,在这种情况下,你必须使用一个平面阵列和做二维数组算术自己:

EDIT: Unless you want to specify the dimensions at runtime, in which case you have to use a flat array and do the 2D array arithmetic yourself:

/* Store sum of matrix a and b in a */
void add(int rows, int cols, int a[], int b[])
{
    int i, j;

    for (i = 0; i < rows; i++)
        for (j = 0; j < cols; j++)
            a[i * cols + j] += b[i * cols + j];
}

这篇关于定义一个矩阵,并把它传递给C中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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