How to add to String Array from inside recursive function in C -
i trying write c function give me binary representation of number n
. function have prints number correctly; string array word
updated same data 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 more elegant way this? doing wrong in code?
here's 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 returned value keep track of end of string
- only compute new character once
- use
putchar
ratherprintf()
, basic performance consideration (printf()
overkill when printing single characters)
note no attempt prevent buffer overflow done, of course added.
Comments
Post a Comment