function returning a string

Hi
I am trying to write a class with a member function that returns a string.
I have this but i get a segmentation fault:
main.cpp
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include "ponto.h"
using namespace std;

int main(){
    Ponto a, b;
	a.set(0,0);
	b.read();
	cout << a.view() << endl;
	cout << b.view() << endl;
}


ponto.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#ifndef PONTO_H
#define PONTO_H
#include <iostream>
#include <cstring>
class Ponto{
private:
    int x, y;
public:
	void read(){
		std::cout << "x = "; std::cin >> x;
		std::cout << "y = "; std::cin >> y;
	}
	char *view(){
		char *output;
		strcpy(output, "lixo");
		return (output); 
	}
    void set(int a, int b){
		x=a;
		y=b;
	}
};
#endif 


Why is that?
Thanks
1
2
3
4
5
char* view() {
   char* output;     // UNINITIALIZED
   strcpy( output, "lixo" );  // Copy the string "lixo" to a random memory location
   return output;
}


Why don't you use C++ strings?
Last edited on
Thanks jsmith and Bazzy.
I used new to solve the error but the Bazzy question makes sense.
This solved my problem.
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
#ifndef PONTO_H
#define PONTO_H
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Ponto{
private:
    int x, y;
		string build_output;
		stringstream sx, sy;
public:
	void read(){
		cout << "x = "; cin >> x;
		cout << "y = "; cin >> y;
	}
	string view(){
		sx << x;
		sy << y;
		build_output =(string)"("+sx.str()+(string)","+sy.str()+(string)")";
		return (build_output); 
	}
    void set(int a, int b){
		x=a;
		y=b;
	}
};
#endif  


Is there a way to avoid the (string) type casting?
Thanks again.
I think that you need to cast only the first element in line 20:
(string)"("+sx.str()+","+sy.str()+")"
should work fine
Last edited on
Actually none of the typecasts are necessary.
I remember when i got this idea from ... i tried line 20 like this before adding sy.str() and sx.str():
build_output ="("+","+")";
In this case i think i have to use the cast:
build_output =(string)"("+","+")";
Last edited on
string provides operator+ that takes a const char* and returns a string, which is why no casts are needed in your original code.

Even if your last example you still don't need the cast if you just

 
build_output = "(,)";


Topic archived. No new replies allowed.