将矩阵传递给函数,C [英] Passing matrix to function, C

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

问题描述

环顾四周后,我构建了一个函数,该函数接受一个矩阵并在其上执行我需要的任何操作,如下所示:

Having looked around I've built a function that accepts a matrix and performs whatever it is I need on it, as follows:

float energycalc(float J, int **m, int row, int col){
...
}

在 main 中定义并填充了数组的大小,但是我无法将其传递给函数本身:

Within the main the size of the array is defined and filled, however I cannot passs this to the function itself:

int matrix[row][col];
...
E=energycalc(J, matrix, row, col);

这会导致编译期间出现警告

This results in a warning during compilation

"project.c:149: 警告:从不兼容的指针类型 project.c:53:注意:应为int **",但是参数的类型为‘int (*)[(long unsigned int)(col +-0x00000000000000001)]’

"project.c:149: warning: passing argument 2 of ‘energycalc’ from incompatible pointer type project.c:53: note: expected ‘int **’ but argument is of type ‘int (*)[(long unsigned int)(col + -0x00000000000000001)]’

并导致分段错误.

非常感谢任何帮助,谢谢.

Any help is greatly appreciated, thank you.

推荐答案

将二维数组传递给 C 中的函数通常会让新手感到困惑.
原因是他们假设数组是指针,并且缺乏对数组如何衰减为指针的理解.
永远记住,当作为参数传递时数组转换为指向其第一个元素的指针.
在函数调用中

Passing two dimensional array to a function in C is often confusing for newbies.
The reason is that they assume arrays are pointers and having lack of understanding how arrays decays to pointer.
Always remember that when passed as an argument arrays converted to the pointer to its first element.
In function call

E = energycalc(J, matrix, row, col);  

matrix 被转换为指向它的第一个元素 matrix[0] 的指针.这意味着传递matrix 等同于传递&matrix[0].请注意,&matrix[0] 的类型是 int(*)[col](指向 col int 数组的指针)和因此是 matrix.这表明函数energycalc 的第二个参数必须是int(*)[col] 类型.将函数声明改为

matrix is converted to pointer to its first element which is matrix[0]. It means that passing matrix is equivalent to passing &matrix[0]. Note that the type of &matrix[0] is int(*)[col] (pointer to an array of col int) and hence is of matrix. This suggest that the second parameter of function energycalc must be of type int(*)[col]. Change the function declaration to

 float energycalc(int col, int (*m)[col], int row, float J);  

并将您的函数称为

 E = energycalc(col, matrix, row, J); 

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

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