converting an int to a char* without sprintf()

This is a discussion on converting an int to a char* without sprintf() within the C Programming forums, part of the General Programming Boards category; I need to write my own function to convert an integer to a string. Code: char* IntToString(int num){ char* str ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    9

    converting an int to a char* without sprintf()

    I need to write my own function to convert an integer to a string.

    Code:
    char* IntToString(int num){
       char* str = "";
       int right;
       
       str = (char*) malloc(10 * sizeof(char));
    
       do {
          right = num % 10;
          
          printf("right = %d\n",right);
    
          switch(right){
    	 case 0:
    	    str = strcat("0",str);
    	    break;
    	 case 1:
    	    str = strcat("1",str);
    	    break;
    	 case 2:
    	    str = strcat("2",str);
    	    break;
             /* ... */
    	 default:
    	    break;
          }
          
          printf("str = %s\n",str);
    
          num /= 10;
       } while(num > 0);
       return str;
    }
    sorta halfway got it, but it keeps segfaulting when trying to concat the 2nd digit from the right. num will always be between 0 and 10000. Any suggestions?

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    Code:
       char* str = "";
       int right;
       
       str = (char*) malloc(10 * sizeof(char));
    Here you define the pointer str to point to an empty string then reassign it to a malloced string of 10 chars. You should just do
    Code:
       char* str=NULL;
       int right;
       
       str = (char*) malloc(10 * sizeof(char));
    or
    Code:
    char str[10]
    But that is not the cause of your segfault.
    Code:
    str = strcat("0",str);
    here is the cause of the segfault. You define a string containing a single char (0) and concatenate it with whats in str.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. NEED HELP READING FILE and PRINTING
    By geoffr0 in forum C Programming
    Replies: 4
    Last Post: 04-16-2009, 05:26 PM
  2. memory leak
    By aruna1 in forum C++ Programming
    Replies: 3
    Last Post: 08-17-2008, 10:28 PM
  3. Replies: 26
    Last Post: 11-30-2007, 02:51 AM
  4. Replies: 2
    Last Post: 03-24-2006, 07:36 PM
  5. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21