Function returns array

i have function that return array and i want to use this array in main () but it doesn't work , There's a run time error !!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string split(string A)
{string arr[10];
int index1=0;
for(int i=0;i<A.length();i++)
{if(A[i]!=';')
arr[index1]+=A[i];
else
index1++;
} 
return arr[10];


int main (){
string arr3={"aa,bb;cc,dd"}
string arr2[10];
arr2[10]=split(arr3);
return 0;



The function does not return an array.

arr[10] is the 11th element of the array named arr. So you're trying to return a string that doesn't actually exist. This is, as you might imagine, a really bad idea.

arr2[10]=split(arr3);
This is a similar mistake. arr2 has ten elements in it. Here they are:

arr2[0]
arr2[1]
arr2[2]
arr2[3]
arr2[4]
arr2[5]
arr2[6]
arr2[7]
arr2[8]
arr2[9]

So how there isn't one called arr2[10]? So when you try to use arr2[10], you're trying to use something beyond the end of your array. That's really bad.

You've not learned enough about arrays to use them safely.

Don't use arrays for this. Arrays are not for beginners. Use vectors.
I understand this point but How could I put an array that a function returns into another array in the main () ?
You would need to create an array that did not get destroyed when the function ends (using new), or create the array in main and pass a pointer to the array into the function.

Do not use arrays for this. Use a vector.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

// split a string into delimited values
// https://cal-linux.com/tutorials/vectors.html
std::vector<std::string> split( const std::string& str, char delimiter = ';' )
{
    std::vector<std::string> result ;
    
    // http://en.cppreference.com/w/cpp/io/basic_istringstream 
    std::istringstream stm(str) ;
    std::string fragment ;
    
    // http://www.cplusplus.com/reference/string/string/getline/
    while( std::getline( stm, fragment, delimiter ) ) result.push_back(fragment) ;

    return result ;
}

int main()
{
    const std::string str = "aa,bb;cc,dd;ee=ff;gg+hh+ii;jj" ;
    
    // http://www.stroustrup.com/C++11FAQ.html#auto
    const auto fragments = split(str) ;
    
    // http://www.stroustrup.com/C++11FAQ.html#for
    for( const auto& part : fragments ) std::cout << part << '\n' ;
}

http://coliru.stacked-crooked.com/a/8d8bd751273b76ed
Topic archived. No new replies allowed.