07-30-2009 05:53 PM
// code not working, as soon as i added my main it gave me errors, can someone fix it
#include <ansi_c.h>
#include <string.h>
char PrintBin(int,char);
int main()
{
PrintBin (int n,*string);
return 0;
}
char *PrintBin (int n, char *string)
{
int len = 0;
if (n < 0) return NULL; // Number must be non-negative
// Recursively call the function for 1 to n-1 bits
if (n > 1) string = PrintBin (n / 2, string);
// Dynamic allocation of memory
if (!string) {
string = malloc (2);
memset (string, 0, 2);
}
else {
len = strlen (string);
string = realloc (string, len + 2);
string[len] = 0;
}
// Print the last bit
sprintf (string + strlen (string), "%d", n % 2);
return string;
}
07-30-2009 11:57 PM