passing 2d array to function

This is a discussion on passing 2d array to function within the C Programming forums, part of the General Programming Boards category; I am having trouble passing an 2d array to a function: Code: int sum (char ar[][], int i, int j){ ...

  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
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    979
    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
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    979
    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, 12: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, 02:32 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21