8250

passing dynamic 2D arrays to function

Question:

I am writing a n x n matrix multiplication program in C where a[][] and b[][] are the inputs and x[][] is the output. a, b and x are malloc'd but I am unsure how to pass the pointers to the multiplication function correctly. below is an outline of what i am trying to do

void multiplication(float a, float b, float x, int n); void main() { float **a, **b, **x; int n; // size of arrays (n x n) multiplication(a, b, x, n); } void multiplication(float a, float b, float x, int n) { // function }

Answer1:

You want <strong>void multiplication(float *a, float *b, float *x, int n);</strong>. Note that generally you should use size_t for indexes and array sizes, and double as your preferred floating point type unless you have specific reason to use float.

Each of a, b and x point to contiguous float values, you will want to dereference these using a[n * x + y].

C99 introduces all kinds of interesting optimization possibilities on top of this, all of which you pretty much can't rely upon in any compiler I know of:

<ul><li><a href="http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html" rel="nofollow">Variable Length Arrays in GCC</a></li> <li><a href="http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=%2Fcom.ibm.vacpp7a.doc%2Flanguage%2Fref%2Fclrc03ary.htm" rel="nofollow">Arrays in XL C/C++ V7.0 (for AIX)</a></li> </ul>

With those, something like this should be possible:

void multiplication(size_t len; // <- semicolon not a mistake double a[len][restrict const len], double b[len][restrict const len], double c[len][restrict const len]);

This pedantic construction would indicate to the compiler that the length of the arrays are are the same, they're 2D, and the sizes are indicated from the calling code at runtime. Furthermore all the arrays are cacheable as they don't <a href="http://developers.sun.com/solaris/articles/cc_restrict.html" rel="nofollow">alias</a> one another.

One can only dream that C continues to be advanced, C99 still isn't fully supported, and many <a href="http://plan9.bell-labs.com/sys/doc/comp.pdf" rel="nofollow">other improvements</a> haven't become mainstream.

Answer2:

you have to pass the address of first element of both matrix in multiplication method

actually the thing is that the elements of an array is arranged like queue means one element after another. so if you know the address of first element then you just increase the index number and you easily get all member of that array.

check <a href="http://www.java2s.com/Tutorial/C/0140__Array/Passarraytofunction.htm" rel="nofollow">this</a>

it might be help you

Answer3:

Well, you must understand pointers for doing this kind of things in C. Here's a simple code:

int n = 10; float * multiply ( float *a, float *b ) { float *ans; int i, j, k; ans = malloc(sizeof(float)*n*n); for (i=0; i<n; ++i) for (j=0; j<n; ++j) { ans[i*n+j] = 0.0; for (k=0; k<n; ++k) ans[i*n+j] += a[i*n+k] * b[k*n+j]; } return ans; } int main() { float *a, *b, *ans; a = malloc(sizeof(float)*n*n); input(&a); b = malloc(sizeof(float)*n*n); input(&b); ans = multiply(a,b); output(ans); return 0; }

If you have trouble understanding the code, please try to brush up your pointer skills. And you can always ask us.

Answer4:

Here is a nice easy way to pass dynamically allocated arrays to a function.

#include <stdio.h> #include <stdlib.h> void Function(int ***Array); int main() { int i, j, k, n=10; //Declare array, and allocate memory using malloc. ( Dimensions will be 10 x 10 x 10) int ***Array=(int***)malloc(n*sizeof(int**)); for (i=0; i<n; i++) { Array[i]=(int**)malloc(n*sizeof(int*)); for (j=0; j<n; j++) { Array[i][j]=(int*)malloc(n*sizeof(int)); } } //Initialize array in a way that allows us to check it easily (i*j+k). for (i=0; i<n; i++) { for (j=0; j<n; j++) { for (k=0; k<n; k++) { Array[i][j][k]=i*j+k; } } } //Check array is initialized correctly. printf("%d\n", Array[4][5][6]); //Pass array to Function. Function(Array); //Check that Function has correctly changed the element. printf("%d\n", Array[4][5][6]); return 0; } void Function(int ***Array) { //Check that Function can access values correctly. printf("%d\n", Array[4][5][6]); //Change an element. Array[4][5][6]=1000; }

I know this is not specific to your matrix multiplication, but it should demonstrate how to pass the array to the function. It is quite likely that your function would need to know the dimensions of the array, so pass those to it as well... void Function(int ***Array, int n) and call the function as Function(Array, n);

Recommend

  • Why can't I delete pointer alone from an array of objects?
  • Memory layout : 2D N*M data as pointer to N*M buffer or as array of N pointers to arrays
  • How does the pointer assignment in strcpy work?
  • C - index applied to pointer to pointer
  • Dereference of Null Pointer
  • How to properly free char** in C
  • Please give example of Rails/Devise/LDAP Devise::LdapAdapter.get_ldap_param usage
  • Pointer to BOOL in Objective C
  • QMenu: Set text color for specific QAction
  • Compare Dictionary
  • Finding regular expressions for languages otherwise described
  • Writing a recursive function on lists in Haskell
  • Gforce min not supported for character in data.table
  • Validity Method for Reference Classes
  • Generating anchors with PyYAML.dump()?
  • How to call a procedure using NHibernate that returns result from multiple tables?
  • Oracle - Second level subquery cannot see field from main query
  • C# - Most efficient way to iterate through multiple arrays/list
  • netsh acl setting (need alternative method - registry settings?)
  • cordova is not defined - cordova.js has already been loaded :: Ionic
  • Remove final comma from string in vb.net
  • Change multiple background-images with jQuery
  • Algorithm for a smudge tool?
  • Can Jackson SerializationFeature be overridden per field or class?
  • Java applet as stand-alone Windows application?
  • Statically linking a C++ library to a C# process using CLI or any other way
  • Weird JavaScript statement, what does it mean?
  • How do you troubleshoot character encoding problems?
  • How to format a variable of double type
  • retrieve vertices with no linked edge in arangodb
  • Android Studio and gradle
  • python regex in pyparsing
  • C# - Getting references of reference
  • -fvisibility=hidden not passed by compiler for Debug builds
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Change div Background jquery
  • apache spark aggregate function using min value
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • Does armcc optimizes non-volatile variables with -O0?
  • How to Embed XSL into XML