-
int to char casting/itoa
Code:
char binary(int number)
{
int remainder, i=0;
char c[1];
char str[22];
do
{
remainder = number%2;
number = number >> 1;
itoa(remainder, c, 32);
str[i] = c[0];
i++;
cout << "\nremainder: " << remainder;
} while (number > 1);
if(number <= 1) {
cout << "Number: " << number;
itoa(number, c, 2);
str[i] = c[0];
i++;
}
str[i] = '\0';
cout << "STRING: " << str << endl;
return *str;
}
hi,
it converts the number into binary but crashes after displaying the last cout statement. Could some1 tell me why is that?
thanks
-
You are returning a pointer to a character. Change your return type to reflect this.
-
You have to ensure that the buffer you pass to itoa can store the string. In this case, you pass a char array of one element (c) which probably won't be large enough. I don't think you really understand itoa; perhaps you should read this page carefully.
>You are returning a pointer to a character. Change your return type to reflect this.
No, he is returning a character.
-
He's prolly trying to return a string. In that case use std::string's instead as returning local non-static character arrays is gonna cause trouble.