Answer the question
In order to leave comments, you need to log in
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
How can I return an array from a function?
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;
}
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 questionAsk a Question
731 491 924 answers to any question