1

This question tells me that I can specify an array of a certain size as a parameter in C. I would presume that this extends to matrices (?) so that I can specify

void foo(char (*p)[10][2]);

to force the caller to pass a 10 by 2 matrix. What I would really like to do is to achieve the following behaviour (using the deliberately dodgy syntax to describe what I want):

void foo(char (*p)[][2]);   

That is, does C provide a way of forcing the caller to pass an n by 2 matrix at compile time?

For context, I have a load of {x,y} data points that I process, which are of varying size. I therefore know there should always be 2 elements in each row and I'd like to check for this at compile time if possible, regardless of the number of rows.

Community
  • 1
  • 1
Ed King
  • 1,833
  • 1
  • 15
  • 32

1 Answers1

1

Your syntax is fine. You can have a pointer to an array of unknown size:

void foo(char (*p)[][2]) { (void)p; }

int main()
{
  char a[10][2];
  char b[25][2];
  char c[50][7];

  foo(&a);
  foo(&b);
  // foo(&c);   // error: incompatible type
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • This demo gives a runtime error but no compile-time error if I uncomment `foo(&c)`? – Ed King Jul 23 '14 at 14:48
  • @EdKing: [Cannot reproduce](http://ideone.com/fxauno) -- I'm getting a nice compilation error. – Kerrek SB Jul 23 '14 at 14:50
  • Ok, I get the behaviour you specify when I keep the `void(c);` line in at the end of your demo. If I remove it, I get the runtime error? – Ed King Jul 23 '14 at 14:53
  • I'm happy with your answer, I'm just wondering why ideone fails if I remove the `void(c);` statement at the end? There are no details for the runtime error that I can see. – Ed King Jul 23 '14 at 15:16