Returning an array from a function

This is a discussion on Returning an array from a function within the C++ Programming forums, part of the General Programming Boards category; this should prove to be a simple question; Am I allowed to return an array from a function? Is so, ...

  1. #1
    Registered User
    Join Date
    May 2003
    Posts
    38

    Returning an array from a function

    this should prove to be a simple question;

    Am I allowed to return an array from a function? Is so, how?

    Here is an example:

    float [] functionName(float x, float y)
    {
    float f_array[2];
    f_array[0] = x;
    f_array[1] = y;

    return f_array;
    }

    in an attempt to answer my question I would say that you are not allowed to do this (but why). And the alternative approach would be to return a pointer to that array?
    chris

  2. #2
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    >>Am I allowed to return an array from a function?
    Nope.

    >>And the alternative approach would be to return a pointer to that array?
    Yep.
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    148
    >>And the alternative approach would be to return a pointer to that array?
    Bad.array f_array has automatic storage.It is gone,when the function returns.

  4. #4
    Registered User
    Join Date
    May 2003
    Posts
    38

    what if....

    What if I have a 2D or 3D array that I would like to return?
    chris

  5. #5
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Code:
    float* func(int size)
    {
      float* array = new float[size];
      // ... etc ...
      return array;
      // Now the caller is responsible for freeing memory.
    }
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  6. #6
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686

    Re: what if....

    Originally posted by cjschw
    What if I have a 2D or 3D array that I would like to return?
    Return a float** or a float*** or (better idea) make a data structure containing such an array (or at least providing a correct interface) which is responsible for memory management, and return that.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  7. #7
    Registered User
    Join Date
    May 2003
    Posts
    38

    thanks

    thanks =)

    (do I need to close this "thread" ?)
    chris

  8. #8
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    >>(do I need to close this "thread" ?)
    Nope.
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  9. #9
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    Much better than returning an array, though, is to return a vecotr (or a vector of vectors for a 2D array, etc.)

    Returning an array by pointer places a burden on the caller; the caller cannot ignore the return value, and the caller must call delete[] (perhaps even in a complicated loop form, in multidimentional arrays).

    Rather than place this burden on the caller, use a vector. This example shows a 2D array of ints created in this fashion:

    Code:
    #include <iostream>
    #include <vector>
    
    typedef std::vector<int> row;
    typedef std::vector<row> array2D;
    
    array2D createArray(int nRow, int nCol){
    	// creates a nRow x nCol array (and initializes to zeros):
    	array2D a2d(nRow, row(nCol)); 
    
    	//Let's make the array more interesting than all 0s:
    	for (unsigned int r = 0; r < a2d.size(); ++r){
    		for (unsigned int c = 0; c < a2d[r].size(); ++c){
    			a2d[r][c] = r + c;
    		}
    	}
    
    	return a2d;
    }
    
    void printArray(const array2D & a2d){
    	for (unsigned int r = 0; r < a2d.size(); ++r){
    		for (unsigned int c = 0; c < a2d[r].size(); ++c){
    			std::cout << "[" << a2d[r][c] << "]";
    		}
    		std::cout << std::endl;
    	}
    }
    
    
    
    
    int main(){
    	array2D a = createArray(5,7);
    	printArray(a);
    }
    The output is:

    Code:
    [0][1][2][3][4][5][6]
    [1][2][3][4][5][6][7]
    [2][3][4][5][6][7][8]
    [3][4][5][6][7][8][9]
    [4][5][6][7][8][9][10]
    This has the following benefits:

    1) No possibility of memory leaks from exceptions
    2) No burden on the caller to deallocate memory
    3) No memory leak if the caller ignores the return value
    4) Array creation is simpler
    5) Array deletion is automatic
    6) By using a2d.size() one can get the number of rows of array a2d, and by using a2d[i].size() one can get the number of columns in row i. So the array's dimensions are stored, copied, etc. with the array itself. This makes it very easy to safely step through an array, and arrays can easily be passed to functions without having to pass the dimensions.
    Last edited by Cat; 07-18-2003 at 03:52 PM.

  10. #10
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    917
    I'd create class templates. One for 1-d arrays, one for 2, and one for 3.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

  11. #11
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    Why 1-d? vector<T> handles that niche nicely.

    Template classes are certainly doable, but I'd have to have a good amount of generic array algorithms, and I'd have to know I was planning on using multiple array types, before I went to that trouble. A few typedefs are not necessarily as generic, but they are usually the simplest answer, and often more than adequate.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 02:01 AM
  2. c++ -- returning an array from function
    By p4plus2 in forum C++ Programming
    Replies: 25
    Last Post: 08-18-2008, 02:48 PM
  3. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  4. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM
  5. Replies: 6
    Last Post: 10-21-2003, 10:57 PM

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