You've chosen to write:
while(ptr!='\0')
That's a funny way of writing:
while (ptr != 0)
or:
while (ptr != NULL)
where you intended to write:
while (*ptr != '\0')
The conventional way of writing *(pointer+cnt)
is pointer[cnt]
.
You can't afford to free the incremented pointer; you must free what was returned by malloc()
— or calloc()
or realloc()
or …
Preserve a copy of the value returned by binary_decimal()
and free the copy (or increment the copy and free the value in ptr
).
You can use either of the two binary_decimal()
functions in the code below:
#include <stdio.h>
#include <stdlib.h>
char *decimal_binary(int);
int main(void)
{
int n;
char *ptr = NULL;
printf("Enter the number\n");
scanf("%d", &n);
ptr = decimal_binary(n);
char *cpy = ptr;
//printing out the characters
while (*ptr != '\0')
{
printf("%c", *ptr);
ptr++;
}
putchar('\n');
free(cpy);
return 0;
}
char *decimal_binary(int n)
{
int cnt = 0;
char *pointer = (char *)malloc(8 + 1);
if (pointer == NULL)
exit(EXIT_FAILURE);
for (int c = 7; c >= 0; c--)
{
int d = n >> c;
if (d & 1)
pointer[cnt] = 1 + '0';
else
pointer[cnt] = 0 + '0';
cnt++;
}
pointer[cnt] = '\0';
return pointer;
}
Or:
char *decimal_binary(int n)
{
int cnt = 0;
char *pointer = (char *)malloc(8 + 1);
if (pointer == NULL)
exit(EXIT_FAILURE);
for (int c = 7; c >= 0; c--)
pointer[cnt++] = ((n >> c) & 1) + '0';
pointer[cnt] = '\0';
return pointer;
}
This could be compressed still more (and even less readably):
char *decimal_binary(int n)
{
char *pointer = (char *)malloc(8 + 1);
if (pointer == NULL)
exit(EXIT_FAILURE);
for (int c = 7; c >= 0; c--)
pointer[7 - c] = ((n >> c) & 1) + '0';
pointer[8] = '\0';
return pointer;
}
And for a buffer of 9 bytes, you could perfectly well allocate a local variable in main()
and pass the address to decimal_binary()
so it does not need to use malloc()
and the main()
does not need to use free:
#include <stdio.h>
#include <stdlib.h>
void decimal_binary(int, char *);
int main(void)
{
int n;
char buffer[9];
char *ptr = buffer;
printf("Enter the number\n");
scanf("%d", &n);
decimal_binary(n, buffer);
while (*ptr != '\0')
{
printf("%c", *ptr);
ptr++;
}
putchar('\n');
return 0;
}
void decimal_binary(int n, char *pointer)
{
for (int c = 7; c >= 0; c--)
pointer[7 - c] = ((n >> c) & 1) + '0';
pointer[8] = '\0';
}