Aidenhjj Aidenhjj - 2 months ago 4
C Question

How to add to String Array from inside recursive function in C

I am trying to write a C function that will give me the binary representation of a number

n
. The function I have prints the number correctly; however I would like the string array
word
to be updated with the same data as is being printed:

#include <stdio.h>
#include <stdlib.h>

#define MAXBIN 100

void printbitsrec(unsigned n, int n_bits, char *w)
{
if (n_bits-- > 0) {
printbitsrec(n >> 1, n_bits, w);
if (n & 1) {
printf("1");
*w++ = '1';
}
else {
printf("0");
*w++ = '0';
}

}
}

void printBits(unsigned n, int n_bits, int ret)
{
char word[MAXBIN];
printbitsrec(n, n_bits, &word[0]);
word[n_bits + 1] = '\0';
if (ret)
printf("\n");
printf("word = %s\n", word);
}

int main() {
printBits(2, 4, 1);
}


Is there a more elegant way to do this? What am I doing wrong in my code?

Answer

Here's my attempt:

#include <stdio.h>
#include <stdlib.h>

#define MAXBIN 100

char * printbitsrec(unsigned n, int n_bits, char *w)
{
    if (n_bits-- > 0) {
        w = printbitsrec(n >> 1, n_bits, w);
        const char c = (n & 1) ? '1' : '0';
        putchar(c);
        *w++ = c;
    }
    return w;
}

void printBits(unsigned n, int n_bits, int ret)
{
    char word[MAXBIN];
    char * w = printbitsrec(n, n_bits, &word[0]);
    *w++ = '\0';
    if (ret)
        printf("\n");
    printf("word = %s\n", word);
}

int main(void) {
    printBits(2, 4, 1);
    return 0;
}

Notable changes:

  • Use a returned value to keep track of the end of the string
  • Only compute the new character once
  • Use putchar rather than printf(), just a basic performance consideration (printf() is overkill when printing single characters)

Note that no attempt to prevent buffer overflow is done, that could of course be added.

Comments