Passing in and returning a string array from a function

Hi there,

Please consider the following code:
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
32
#include <iostream>
#include <string.h>

using namespace std;

string convertName(string arrayOne[], int arraySize)
{
	string arrayTwo [arraySize];
	string chainName = "chain";

	for(int i = 0; i < arraySize; i++){

		arrayTwo[i] = arrayOne[i] + chainName;

		//cout << finalArray[i] << endl;
		}
		return arrayTwo;
}

int main(){

	string mainArray [] = {"three", "two", "one"};
	int arraySize = (sizeof(mainArray) / sizeof(string));
	string finalArray [arraySize];

	finalArray = convertName(mainArray, arraySize);

	for(int i = 0; i < arraySize; i)
	cout << finalArray[i] << endl;

	return 0;
}


and I get the error

[output]convertName1.cxx: In function
If you want std::string you should include <string> ( without .h )
You are returning an array from a function returning a single string.
From the way you are using arrays, I'd suggest you to use vectors instead.
( Automatic arrays aren't assignable and can't be returned )
I'm not rly pro in C++ but I think you should return a pointer instead of an array. Like this.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string.h>

using namespace std;

string *arrayTwo;

string *convertName(string *arrayOne, int arraySize)
{
    
	arrayTwo = new string[arraySize]; 
	string chainName = " chain";
	//string* point = arrayTwo;

	for(int i = 0; i < arraySize; i++){

		arrayTwo[i] = arrayOne[i] + chainName;

		//cout << arrayTwo[i] << endl;
		}
		
		
             //return point;
		return arrayTwo;
		
}

int main(){

	string mainArray [] = {"three", "two", "one"};
	int arraySize = (sizeof(mainArray) / sizeof(string));
	string* finalArrayP, finalArray[arraySize];

	finalArrayP = convertName(mainArray, arraySize);
	
	
	
	for(int i = 0; i < arraySize; i++)
	cout << finalArrayP[i] << endl;

    system("pause");
    delete [] arrayTwo;
	return 0;
}


I'm not sure is the delete correct. It might cause a memory leak. :/
Last edited on
Your delete is wrong, it won't cause a memory leak, it will simply crash the program. Also, in the function assigning arrayTwo to a pointer doesn't do anything, arrays ARE pointers. As Bazzy said, go for a std::vector instead.
Topic archived. No new replies allowed.