How to return an array?

Hi all,

how do I declare an array of functions like I want to return an array from my function

For example

char h[](char k, int y)

The above wont work, any suggestions?
1
2
3
4
5
6
7
8
9
10
char* returnArray(const int size)
{
    return new char[size];
}

int main(int argc, char *argv[])
{
    char* array = returnArray(5);
    return 0;
}
You can't return an array, you can return a pointer to an array. But be careful because local arrays (which are not created dynamically with new) gets destructed as soon as the function returns. So this won't work:
1
2
3
4
char *bad_array_return() {
    char a[] = { 1, 2, 3, 4 };
    return a; //BAD, the returned pointer will be invalid
}

Using dynamic arrays:
1
2
3
4
char *dynamic_array_return() {
    char *a = new char[4];
    return a; //the returned pointer will be fine, but make sure you delete it after use.
}

The best is to use std::vector (or any other STL container)
1
2
3
4
std::vector<char> vector_return() {
    std::vector<char> res;
    return res;
}


http://www.cplusplus.com/reference/stl/
Topic archived. No new replies allowed.