-1
int n = 10;
char *s;
while (n > 0) {
  s[strlen(s)] = n % 2 + 48;
  n = n / 2;
}
printf("%s", s);

I tried to convert a series of 0's and 1's into string but, I didn't get the output as expected, eventhough, this logic is correct. What goes wrong here?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
Surya
  • 19
  • 6

1 Answers1

0

A better way would be to use the sprintf() function.

#include<stdio.h> 
int main() 
{ 
    char result[50]; 
    int n = 10; 
    sprintf(result, "%d", n); 
    printf("The string for the n is %s\n", result); 
    return(0);
} 
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Suyash
  • 375
  • 6
  • 18
  • 2
    Note that the code in the question is actually trying to produce the binary representation of the value (`1010` for decimal 10, for example). Unfortunately, `sprintf()` doesn't have a standard 'format as binary' conversion specifier. – Jonathan Leffler Jan 12 '20 at 05:13
  • @JonathanLeffler I'm sorry, should have read that more carefully – Suyash Jan 12 '20 at 05:16
  • Me too — the duplicate may not be the best for 'convert integer to string using binary notation'. I'm working on finding additional questions to make as a duplicate. – Jonathan Leffler Jan 12 '20 at 05:17
  • @JonathanLeffler I'm not disputing the duplicate(s) here but, having just revisited this, I noticed that the OP's code *does* actually create the binary representation of a given `n` - just that it's **backwards**! I found that interesting, at least. – Adrian Mole Jan 12 '20 at 15:40
  • @AdrianMole — It's always easiest to generate the least significant digit first (`n % base` gives you the least significant digit). One way around that is to reverse the string after generating the digits. Another is to recurse on `n / base` (if it is greater than zero) before adding `n % base` to the output. The OPs code doesn't null terminate the string. The question doesn't show the output received and explain what's wrong with it, either (nor does it include a newline at the end of the output as it should for comfort). – Jonathan Leffler Jan 12 '20 at 15:45
  • @JonathanLeffler Indeed! But when I first came across the post (and made my comment), I failed to spot the reversal - and I feel embarrassed that I could have made a cleaner post (answer) and saved time and trouble. That I was, at the time, in an airport lounge between two long flights is no excuse, but may explain my (temporary?) lack of focus! – Adrian Mole Jan 12 '20 at 16:21