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.