How to pass an array to a function?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Anthony Masi
    New Member
    • Jan 2011
    • 1

    How to pass an array to a function?

    I'm attempting to pass an array to a function and I'm getting "undefined reference to fillArray(int*) " when attempting to build. I've been searching online all evening to know avail.

    This program is supposed to fill an array with randomly generated numbers, but I stripped it down to this code to find what was giving me an error. I'm using eclipse C++.

    Here's a code snippet:

    Code:
    void fillArray(int);
    
    int main ()
    {
    	int const size = 20;
    	int array1[size], array2[size], array3[size];
    	fillArray(array1);       	
    }
    
    void fillArray(int blankArray) {
    	cout << "Testing 1 2 3 Testing";
    }
    Thanks in advance, sorry if it's extremely obvious. :p
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    you are passing an array into the function so the function header should be
    Code:
    void fillArray(int blankArray[]) {

    Comment

    • alexis4
      New Member
      • Dec 2009
      • 113

      #3
      Or you can declare a pointer to point to the element [0] of the array.

      Code:
      #define _SIZE  20
      void fillArray(int *ptr);
       
      int main ()
      {
          int array[_SIZE];
          int *p;
          p = &array[0];
          fillArray(p);           
      }
       
      void fillArray(int *ptr) {
        for(int i = 0; i < _SIZE; i++)
        {  
          *(ptr + i) = i;  //array[i] = i
        }
      }

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Note that when you pass an array to a function all you pass is the name of the array. In C/C++ the name of an array is the address of element 0. Therefore, your funciton argument is a pointer to element 0.

        However, once ytou are inside your function you have no idea how many array elements there are. This is called decay of array. For this reason, you will need a second function argument for the number of elements.

        Comment

        Working...