Conversion to string from int

Hi, why is the output some garbage value at the start of the first 2 bits? and then fine for the rest of the bits? I don't understand. Hope someone is able to help! Thanks.

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

template<size_t k>
class bitarr
{
public:
	bitarr()
	{
		array = new int[k];
		str = new char[k];
		memset(array, 0, sizeof(array));

	}
	bitarr& set(size_t pos, bool val = true)
	{
		array[pos] = val;
		return *this;
	}
	const std::string to_string()
	{
		std::string str;
		for (unsigned int i = k; i-- > 0;)
		{
			str.push_back('0' + array[i]);
		}
		return str;
	}
private:
	int* array;
	char* str;
};
int main()
{
	bitarr<5> bitarr;
	bitarr.set(1);
	bitarr.set(2);
	try
	{
		const std::string st = bitarr.to_string();
		if (st != "00110")
		{
			std::cout << st << std::endl;
			throw std::runtime_error{ "Cannot convert to string." };
		}
	}
		catch (...)
		{
			std::cout
				<< "Test " << std::endl;

		}
}
Last edited on
That memset looks wrong. array is an int pointer, size 8 bytes (probably), but you want to write over all the int values in the array, which for 5 int values would be 40 bytes.
memset(array, 0, sizeof(int) * k);


Also, I see no use of this anywhere:
char* str;
so just remove it from the code to keep things simple and easier to read.
Topic archived. No new replies allowed.