trying to return char* not working

I know I am overlooking something really really obvious here, but I cannot figure it out...

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
#include <iostream>
#include <string>

using namespace std;

int intFunc() {
	int myInt;
	printf("enter int: ");
	cin >> myInt;
	cout << myInt;
	return myInt;
}

char *charPtrFunc() {
	char myCharPtr[100];
	printf("enter characters: ");
	cin >> myCharPtr;
	cout << myCharPtr;
	return myCharPtr;
}

string stringFunc() {
	string myString;
	printf("enter string: ");
	cin >> myString;
	cout << myString;
	return myString;
}
int main() {
	while (1) {
		cout << endl << "intFunc returns: " << intFunc() << endl;
		cout << endl << "charPtrFunc returns: " << charPtrFunc() << endl;
		cout << endl << "stringFunc returns: " << stringFunc() << endl;
	}

	return 0;
}


enter int: 22
22
intFunc returns: 22
enter characters: sss
sss
charPtrFunc returns: ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╚█T►☺╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠
╠╠╠╠╠L ╠╠╠╠╠╠╠╠
enter string: cvf
cvf
stringFunc returns: cvf
enter int:
You're returning just a pointer while the array itself gets freed. An alternative is to have it return nothing, and instead accept a char pointer to an array created in main as an argument, which it will use to store the input.
Last edited on
I will pass the char array as parameter like you suggested. Just one question, though...

Aren't the "int" and the "string" freed also before return?

So it sounds like the general rule is that normal (non-pointer) local variables live long enough to be returned (at least live long enough to return the value to something in main) but anything a pointer points to is gone by the time the function returns?
just return static char [] from the function
a copy of the int or string is passed as the return value, so it's okay. The problem with arrays is that only the pointer is passed while the array if freed. If you were to make an object that contains an array, you could return that.
The problem with arrays is that only the pointer is passed while the array if freed.

Answers my question exactly!

thank you both, kevinchkin and Gumbercules
Topic archived. No new replies allowed.