The problem is likely that you didn't allocate space for the char* when you moved it inside the function. You could declare str as char str[100] if you are using mike_g's version, but I would use a bitset as I mentioned in that thread:
Code:
std::string getbinary(int num)
{
return std::bitset<32>(num).to_string<char, std::char_traits<char>, std::allocator<char> >();
}
The ugliness of the to_string method will be fixed in later C++ standard.
For fun, I welcome people to comment on this "super" version, which is probably more than you need:
Code:
#include <iostream>
#include <bitset>
#include <string>
#include <climits>
#include <limits>
template<bool truncate_zeroes, size_t bits>
std::string get_binary_impl(unsigned long val)
{
std::string s(std::bitset<bits>(val).to_string<char, std::char_traits<char>, std::allocator<char> >());
return truncate_zeroes ? (val == 0 ? "0" : s.substr(s.find_first_not_of('0'))) : s;
}
template<size_t bits>
std::string get_binary(unsigned long val)
{
return get_binary_impl<false, bits>(val);
}
std::string get_binary(unsigned long val)
{
return get_binary_impl<true, sizeof(unsigned long)*CHAR_BIT>(val);
}
int main()
{
std::cout << get_binary(0) << '\n';
std::cout << get_binary(5) << '\n';
std::cout << get_binary<8>(0) << '\n';
std::cout << get_binary<8>(5) << '\n';
std::cout << get_binary(1431655765) << '\n';
std::cout << get_binary(std::numeric_limits<unsigned long>::max()) << '\n';
}