-1

So i was writting a simple c code which coverts a number into a string, and there is one thing that is unclear to me. On this code:

    void itos(int a,char *p){
    int pom = a;
    do{
       p++;
       pom/=10;
    }while(pom);
    *p = '\0';
    do{
       pom = a%10 + '0';
       *--p = pom;
       a/=10;
      }while(a);
     }

i keep getting segmentation faults and i don't understand why. The string is passed by adress, so shouldn't the string from the main have the accses to string in the function? On the other hand this code works pefectly:

     char *itos(int a,char *p){
     int pom = a;   
     do{
        p++;
        pom/=10;
     }while(pom);
    *p = '\0';
    do{
        pom = a%10 + '0';
        *--p = pom;
        a/=10;
    }while(a);
    return p;

   }

If somone could explain me the diffrence (especially why the first one isn't working) i'd be extremlly greatful.

sale
  • 41
  • 6
  • 3
    The two differs just the return value, please also post the code that calls this function. – fluter May 11 '16 at 12:33
  • Already got the answer. The pointer wasnt initialized corectly. Thanks for the help! – sale May 11 '16 at 12:50

1 Answers1

0

The two function only differs by the return value, one returns the pointer p, the other returns nothing. So make sure the pointer you passed in are initialized to valid address, that is, it points to a buffer:

char str[100];
itos(a, str);

or

char *str = malloc(100);
itos(a, str);

To convert integer to string, you could just print it:

char str[100];
int n;
snprintf(str, sizeof str, "%d", n);
fluter
  • 13,238
  • 8
  • 62
  • 100