Thread: int to char casting/itoa

  1. #1
    eat my shorts!
    Join Date
    Apr 2002
    Posts
    294

    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
    Games Reviews Previews Desktop Themes Downloads Paintball Forums Shareware Freeware and much more

    The best in Technology and Gaming News

    www.back2games.com

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    You are returning a pointer to a character. Change your return type to reflect this.

  3. #3
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    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.
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  4. #4
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    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.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 08:36 PM
  2. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  3. Working with random like dice
    By SebastionV3 in forum C++ Programming
    Replies: 10
    Last Post: 05-26-2006, 09:16 PM
  4. Game Won't Compile
    By jothesmo in forum C++ Programming
    Replies: 2
    Last Post: 04-01-2006, 04:24 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM