K
K
KindOfHeaven2018-04-02 21:46:20
C++ / C#
KindOfHeaven, 2018-04-02 21:46:20

How to return an array of C++ strings?

How can I return an array of strings from a function?

string *func(string s) {
    static string str[] = {"qwe", s ,"\0"};
    return str;
}
int main()
{
    string exp = "1234566";
    string arr[0] = func(exp); // Здесь ошибка - Array initializer must be an initializer list
    return 0;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2018-04-02
@jcmvbkbc

How can I return an array from a function?

Learn the materiel: you cannot return an array from a function. You can return a pointer to an array or a structure containing an array.
On the left side of this expression is an array of zero elements. On the right is a pointer to string.
What did you mean by this expression?

M
Mercury13, 2018-04-03
@Mercury13

WARNING: You have a couple of thin spots.
ONCE. remember that string literals in C are null-terminated strings, and "\0" will in fact be an empty string. A string of one null character can be cast into string — for example, with the string(begin, end) constructor or s += '\0', but not with the string(const char*) constructor.
TWO. This static will be initialized on the first call. The second call will return the same array.
THREE. It is better to pass the line as string *func(const string& s) {}
To the point. An array is a rather complex object, and the question arises: who will own this array after it leaves the limits of the function?
1. Owns runtime system. This is perfectly answered by Roman , I will give only the key line.
DO NOT USE: if the array is used in someone's "horse" constructors-destructors of static objects (due to the lack of modules, C++ does not allow you to set the order of creation / destruction of static objects at the language level).
2. Owns some object.

string *func(string s) {
    static string* ar = nullptr;
    if (ar) delete[] ar;
    ar = new ar[3];
    ar[0] = "qwe";
    ar[1] = s;
    ar[2].clear();
    return ar;
}

DO NOT USE: well, it's up to you to deal with this object, how long it will live and how long it will keep the array. In this case, each new call destroys the old array. (The code is clumsy because the last array is not destroyed.)
3. Owner is the caller. It is better to use some std::vector for such purposes.
vector<string> func(string s) {
    vector<string> r;
    r.reserve(3);
    r.push_back("qwe");
    r.push_back(s);
    r.push_back(std::string());
    return r;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question