954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to pass reference of a 2-D matrix to a function in C

I want to pass a 2D matrix to a function in C which modifies the elements of the matrix and the modifications should be effective in the calling function.
How to achieve this in C.

venuaccha
Newbie Poster
9 posts since May 2007
Reputation Points: 29
Solved Threads: 0
 

All arrays, including multi-deminensional arrays, are passed by address, never by value. Passing a 2d array is similar to 1d array, the sedond deiminsion is optional.

void foo(int array[10][10])
{
  // blabla
}

or

void foo(int array[10][])
{
  // blabla
}

int main()
{
   int array[10][10];
   // now pass the array to the function
   foo( array );
   return 0;
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

What if the size of the matrix is variable one.how to define a function then.
All arrays, including multi-deminensional arrays, are passed by address, never by value. Passing a 2d array is similar to 1d array, the sedond deiminsion is optional.

void foo(int array[10][10])
{
  // blabla
}
 
or
 
void foo(int array[10][])
{
  // blabla
}
 
int main()
{
   int array[10][10];
   // now pass the array to the function
   foo( array );
   return 0;
}
venuaccha
Newbie Poster
9 posts since May 2007
Reputation Points: 29
Solved Threads: 0
 

In addition to the two choices I posted previously you could use the stars

void foo(int **array)
{

}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

> void foo(int array[10][])
Should be
void foo(int array[][10])
It's only the left-most dimension which can be left empty.

> void foo(int **array)
Whilst this does allow variability, it doesn't allow you to do

int small[10][10];
int large[100][100];
foo( small );
foo( large );


There is no good way to write a single function which would accept small and large. http://c-faq.com/aryptr/ary2dfunc2.html

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You