Thread: Arrays in functions

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    10

    Question Arrays in functions

    How would i use an array ( that is defined in the main() ) in a function? how would i define it?
    for example:
    Code:
    void Function( int grid[4][4] );
    
    int main()
    {
         int array[4][4];
         Function(array[4][4]);
         return 0;
    }
    
    void Function( int grid[4][4] )
    {
         printf("  %d  %d  %d  %d\n  %d  %d  %d  %d\n  %d  %d  %d  %d\n  %d  %d  %d  %d\n",  grid[0][0], grid[0][1], grid[0][2], grid[0][3], ... , grid[3][3]);
    }
    this is a watered down version of what im working on, but i need array[4][4] to equal grid[4][4], and all the numbers in the arrays to match up. is this even possible? or will i have to copy and paste the printf line throughout my code whenever it is needed?

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You have it almost nailed down . . . you just need to call the function like this:
    Code:
    Function(array);
    You see, Function takes a variable of type int [4][4]. "array" matches that type. But "array[4]" is of type int[4], and "array[4][4]" is of type int, never mind that both of those indices are out of bounds.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    May 2008
    Posts
    10
    Thanks alot for the quick reply

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. functions using arrays
    By trprince in forum C Programming
    Replies: 30
    Last Post: 11-17-2007, 06:10 PM
  2. Passing arrays of pointers into functions
    By ashley in forum C Programming
    Replies: 5
    Last Post: 01-13-2007, 06:48 PM
  3. storage class, arrays, functions and good layout
    By disruptivetech in forum C Programming
    Replies: 4
    Last Post: 12-02-2005, 02:34 PM
  4. functions and arrays
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 03-14-2002, 09:57 AM
  5. elements of arrays; functions
    By sballew in forum C Programming
    Replies: 6
    Last Post: 09-03-2001, 01:48 AM