exc/k&r/04-funcs-and-prog-struct/04-12.c

38 lines
718 B
C
Raw Normal View History

2023-07-14 12:50:17 +02:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void itoar(char *s, int x);
/* converts first arg to int, puts it to output with itoar */
int main(int argc, char *argv[])
{
if (argc < 2)
return 1;
int x = atoi(argv[1]);
char s[strlen(argv[1])+1];
itoar(s, x);
printf("%s\n", s);
return 0;
}
char * utoar(char *s, unsigned x);
/* itoa: writes int x to string s in decimal
* recursive implementation */
void itoar(char *s, int x)
{
unsigned y = (x < 0) ? *(s++) = '-', -x : x;
s = utoar(s, y);
*s = '\0';
}
/* utoar: helper for itoa */
char * utoar(char *s, unsigned x)
{
if (x / 10)
s = utoar(s, x / 10);
*s = x % 10 + '0';
return s+1;
}