Thread: Pass an array to a function by reference?

  1. #1
    Registered Abuser Loic's Avatar
    Join Date
    Mar 2007
    Location
    Sydney
    Posts
    115

    Pass an array to a function by reference?

    Is it possible to pass an array by reference to a function?

    Like so...
    Code:
    void clearboard(int& sqr[])
    {
         for (int i=1; i<11; i++)
             sqr[i] = 'X';
    }
    
    void board(int& sqr[])
    {
         cout << sqr[1] << " | " << sqr[2] << " | " << sqr[3]
              << sqr[4] << " | " << sqr[5] << " | " << sqr[6]
              << sqr[7] << " | " << sqr[8] << " | " << sqr[9];
    }
    
    int main(int argc, char *argv[])
    {
      int sqr[10];
      clearboard(sqr);
      board(sqr);
      system("PAUSE");	
      return 0;
    }
    For some reason it wont let me compile it...
    declaration of `sqr' as array of references
    In function `void clearboard()':
    `sqr' undeclared (first use this function)
    (Each undeclared identifier is reported only once for each function it appears in.)
    At global scope:

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Arrays are passed by reference automatically, no & needed.

    Also note that your for loop is incorrect. It should stop at i < 10, since sqr has a size of 10 and indexes start at 0.

  3. #3
    Registered Abuser Loic's Avatar
    Join Date
    Mar 2007
    Location
    Sydney
    Posts
    115
    Oh right didn't know that... thanks,



    Thanks didn't see that... stupid mistake... lol

  4. #4
    Registered User
    Join Date
    Jan 2007
    Posts
    330
    To just answer the question

    Code:
    void func(char (&arr)[1024])
    {
    }
    reference to an array of 1024

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Library troubles with makefile
    By mslate in forum Linux Programming
    Replies: 17
    Last Post: 07-23-2009, 04:43 PM
  2. Pass struct array to function
    By aditya_t90 in forum C Programming
    Replies: 4
    Last Post: 03-30-2009, 11:54 AM
  3. Speed test result
    By audinue in forum C Programming
    Replies: 4
    Last Post: 07-07-2008, 05:18 AM
  4. Replies: 1
    Last Post: 10-21-2007, 07:44 AM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM