Thread: passing 2d array to function

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    22

    passing 2d array to function

    I am having trouble passing an 2d array to a function:
    Code:
    int sum (char ar[][], int i, int j){     // line 20 
     int x=0;
     if (ar[i][j] == 'a') 
      x++;
     if (ar[i][j] == 'b') 
      x+=2;
     if (ar[i][j] == 'c') 
      x+=3;
    return x;
    } 
    
    ...
    for (i=0;i<10;i++)
     for(j=0;j<10;j++)
      int total= sum(ar,i,j); // line 40
      printf("total is %d",total);
    ...
    I am getting:
    -array type has incomplete element type (line 20)
    -type of formal parameter 1 is incomplete (line 40)

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    You can't leave all the dimensions of an array empty in your prototype; just the first, e.g.:
    Code:
    void f(int x[][5]);

  3. #3
    Registered User
    Join Date
    Mar 2008
    Posts
    22
    cool, so I can place any number as the second dimension ?

  4. #4
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    Well, the array you pass in must match the prototype (except of course for the first dimension, which you needn't provide). So yes, you can place any (integral) number that you'd like, but then you must pass in an array of that size. You can't make a function that accepts any size 2d array.

    You can get around this by faking a 2d array with pointers, but that's slightly more complex.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 10-21-2007, 07:44 AM
  2. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  3. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  4. passing 2D array to a function
    By ashesh in forum C Programming
    Replies: 4
    Last Post: 06-09-2003, 11:16 PM
  5. passing an array to a function (2d array)
    By revelation437 in forum C Programming
    Replies: 5
    Last Post: 03-11-2003, 03:32 PM