Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing matrix to function, C

Tags:

c

function

matrix

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){
...
}

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: 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)]’

and leads to a segmentation fault.

Any help is greatly appreciated, thank you.

like image 982
Narlok Avatar asked Nov 28 '25 01:11

Narlok


1 Answers

The function should be declared like

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

if your compiler supports variable length arrays.

Otherwise if in declaration

int matrix[row][col];

col is some constant then the function can be declared the following way

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

provided that constant col is defined before the function.

Your function declaration

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

is suitable when you have an array declared like

int * matrix[row];

and each element of the array is dynamically allocated like for example

for ( int i = 0; i < row; i++ ) matrix[i] = malloc( col * sizeof( int ) );
like image 163
Vlad from Moscow Avatar answered Nov 30 '25 15:11

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!