-2

How can I pass my matrix to a function in another file to do something? I allocated my matrix containing structs like this:

   typedef struct {
        int x;
        int y;
        int z;
    } myStruct;
    
    myStruct(*matrix)[COL] = malloc(ROW*sizeof*matrix);
joy
  • 17
  • 4
  • To pass the pointer, just pass it: `func(matrix)`. Declare it the same way as shown in your post. Did you not try this? – Tom Karzes Dec 26 '20 at 22:16
  • @TomKarzes I tried, but my function should be in another file. Not in the file containing main. So, gives me this error: _implicit declaration of function ‘myFunction’_. Maybe because it can't see the struct (?). – joy Dec 26 '20 at 22:44
  • As with any function, you need to declare it before you can call it. The problem has nothing to do with the particular argument type you're passing. Do you know how to declare a function? – Tom Karzes Dec 26 '20 at 23:13

2 Answers2

0

A matrix is an array of arrays, so you could use a pointer to a pointer to mystruct, as well and the number of rows and columns so the function knows how to handle it:

void myfunction(mystruct** matrix, int rows, int columns) {
    // Your logic goes here...
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • I tried, but my function should be in another file. Not in the file containing main. So, gives me this error: _implicit declaration of function ‘myFunction’_. Maybe because it can't see the struct (?). – joy Dec 26 '20 at 22:41
  • @joy That's unrelated to the struct. You're calling the function before it's formally defined. See, e.g. https://stackoverflow.com/q/8440816/2422776 for details. – Mureinik Dec 26 '20 at 22:44
  • No, it is defined, It's the definition that gives me problems. – joy Dec 26 '20 at 22:52
0

Use VLA from C99.

void myfunction(int rows, int cols, myStruct matrix[rows][cols]) {
  ...
}
tstanisl
  • 13,520
  • 2
  • 25
  • 40
  • from, not form. And maybe should mentionin addition to being C99, VLA is also optional from C11 and beyond – ryyker Dec 26 '20 at 22:34
  • @ryyker, yes, it got optional in C11. That is sad because it greatly simplifies handling multi-dim arrays. Still most compilers support it and there is a macro to check if VLA is supported. – tstanisl Dec 26 '20 at 22:40