0

I have the following working putchar() functions for integers:

void write_uint(unsigned n) {
    if (n / 10) write_uint(n / 10);
    putchar(n % 10 + '0');
}

void write_int(int n) {
    if (n < 0) {
        putchar('-');
        write_uint(-(unsigned)n);
    }
    else write_uint(n);
}

I am trying to modify it to convert the integer to a char array using pointers instead of writing to console as follows:

void write_uint(unsigned n, char *p) {
    if (n / 10) write_uint(n / 10, p);
    *p++ = n % 10 + '0';
}

void write_int(int n, char *p) {
    if (n < 0) {
        *p++ = '-';
        write_uint(-(unsigned)n, p);
    }
    else write_uint(n, p);
}

int n = 123456789;
char *str = malloc(13000), *p = str;

write_int(n, p);
*p++ = '\n';

Then print the string, but all I get is a bunch of empty lines.

Any help is appreciated

ceferrari
  • 1,597
  • 1
  • 20
  • 25

2 Answers2

1

In write_int() and write_uint() you increment p but because you have passed char *p, that incrementation is not passed back to the caller. So in the last line of your sample code, p is still equal to str and so you get the empty line.

You can modifiy your code in one of these ways:

  1. pass a char ** instead of a char *

    void write_uint(unsigned n, char **p) {
        if (n / 10)
            write_uint(n / 10, p);
        **p = n % 10 + '0';
        (*p)++;
    }
    
    void write_int(int n, char **p) {
        if (n < 0) {
            **p = '-';
            (*p)++;
            write_uint(-(unsigned)n, p);
        }
        else
            write_uint(n, p);
    }
    
    ....
    write_int( n, &p );
    *p++ = '\n';
    
  2. return the modified pointer

    char *write_uint(unsigned n, char *p) {
        if (n / 10)
            p = write_uint(n / 10, p);
        *p++ = n % 10 + '0';
        return p;
    }
    
    char *write_int(int n, char *p) {
        if (n < 0) {
            *p++ = '-';
            p = write_uint(-(unsigned)n, p);
        }
        else 
            p = write_uint(n, p);
        return p;
    }
    
    ....
    p = write_int( n, p );
    *p++ = '\n';
    

Of course, as #pm100 has stated, you should add a NUL after the '\n' too

Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33
-1

you certainly need to zero terminate str

*p++ = 0;

Or if you prefer

*p++ = '\0';
pm100
  • 48,078
  • 23
  • 82
  • 145