cout affects wrongly to char* variant

Write your question here.

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
  #include <iostream>
#include <stdlib.h>
#include <cstring>
using namespace std;
class CInteg
{
public:
	enum flag { Exact, Estimate };
	CInteg(int i = 1, flag f = Exact);
	~CInteg();
private:
	int num;
	flag prec;
public:

	CInteg operator+(const CInteg  n) const
	{
		CInteg temp;
		if (this->prec == CInteg::Estimate || n.prec == CInteg::Estimate)
			temp.prec = CInteg::Estimate;
		else
			temp.prec = CInteg::Exact;
		temp.num = num + n.num;
		return temp;
	}

	char* print()
	{
		char* pstr{};
		char out[30];
		_itoa_s(num, out, 30, 10);
		pstr = out;
		if (this->prec == CInteg::Estimate)
			strcat_s(pstr, strlen(pstr) + 3, " E");
		return pstr;
	}
};

CInteg::CInteg(int i, flag f) : num{ i }, prec{ f }
{
}


CInteg::~CInteg()
{
}
inline CInteg operator+(const int a, const CInteg i)
{
	CInteg temp(a);
	return temp + i;
}
int main()
{
	char* test{ "Peter" };
	cout << test << endl;
	CInteg i(5, CInteg::Estimate);
	i = i + 10;
	test = i.print();
	cout<<test<<endl;
	CInteg j(221312123,CInteg::Estimate);
	cout<<j.print()<<endl;
	return 0;
}

The first cout works OK.
The second and third cout gives rubish.
Please help me
If you create a local variable inside a function, when that function ends the memory that variable is using will be reused.

So in the function print(), the array char out[30]; gets overwritten after the function ends. So you have a pointer to some memory that's being overwritten.



Are you using char arrays instead of strings for a good reason? C++ does have string types, which come with helpful functions for turning numbers to strings and string to numbers.
Topic archived. No new replies allowed.