传递矩阵功能,C [英] Passing matrix to function, C

查看:243
本文介绍了传递矩阵功能,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){
...
}

在该阵列的主要的大小被定义和填充,但是我不能passs此函数本身

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:警告:从通过energycalc的论点2
  兼容的指针类型project.c:53:注意:预计'诠释**,但
  参数的类型为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)]’

和导致分段错误。

任何帮助是极大AP preciated,谢谢你。

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);  

矩阵转换为指针,以这是它的第一个元素矩阵[0] 。这意味着,通过矩阵,相当于将&放大器;矩阵[0] 。需要注意的是类型&放大器;矩阵[0] INT(*)[COL] (指向数组的指针的山坳 INT),因此是矩阵。这表明函数的第二个参数 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天全站免登陆