I just started with C and I am trying to create a program which takes a number and converts it to binary using this method (from indepth.dev):
To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order. (...) Now, we simply need to write out the remainder in the reverse order —1100. So, 12 in decimal system is represented as 1100 in binary.
I am trying to make the array dynamic in size. Coming from Python this is a bit confusing, because in Python you can just append to a list.
Here is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int *ptr, n, i;
ptr = (int*)malloc(1 * sizeof(int));
printf("Enter a number to convert: ");
scanf("%d", &n);
for (i = 0; n>0; i++)
{
ptr = realloc(ptr, i * sizeof(int));
ptr[i] = n % 2;
n = n/2;
}
for(i=i-1; i>= 0; i--)
{
printf("%d", ptr[i]);
}
free(ptr);
return 0;
}
When I run the program and enter a number it doesn't output anything. If I do the same with a fixed array size it works. Why is this happening?
reallocat the first loop step? And the next?log10()to calculate the number of needed array elements and allocate it only once?