Is there any way to return an array from a function? More specifically, I've created this function:
char bin[8];
for(int i = 7; i >= 0; i--)
{
int ascii='a';
if(2^i-ascii >= 0)
{
bin[i]='1';
ascii=2^i-ascii;
}
else
{
bin[i]='0';
}
}
and I need a way to return bin[]
.
You'll want to pass by reference, as follows:
You are really asking the wrong question. If you want to do string processing in C++, use the std::string and/or std::vector classes, not arrays of char. Your code then becomes:
Your array is a local variable allocated on the stack. You should use
new []
to allocate it on the heap. Then you can just say:return bin;
. Beware that you will have to explicitly free it withdelete []
when you are done with it.You can't do that but you can:
Similar implemented to @ari's answer, i want to say there is already a boost solution,
boost::array
solving your problem:[I'm not sure what you want to do with that algorithm though, but note that i think you want to do
1 << i
(bit-wise shift) instead of2 ^ i
which is not exponentiation in C++.]Boost array is a normal array, just wrapped in a struct, so you lose no performance what-so-ever. It will also be available in the next C++ version as
std::array
, and is very easy to do yourself if you don't need thebegin()
/size()
/data()
-sugar it adds (to be a container). Just go with the most basic one:But as usual, use the tools already written by other people, in this case
boost::array
. It's also got the advantage of being an aggregate (that's why it has no user declared constructor), so it allows initializing with a brace enclosed list:If you want to return a copy of the array (might make sense for small arrays) and the array has fixed size, you can enclose it in a struct;
Or just use a std::vector as has been already suggested.