I am trying to assign values to elements in dynamic array, but can't find solution. There are many videos showing how it works if value is entered by the user via scanf, but here it's not the case. I really tried to find info here and there and solve it myself so any help will be highly appreciated. Here is my code:
//Program co convert decimal number to binary and count zeros
int main()
{
int decimalNum;
int *binaryNum;
int zeroCounter = 0;
int i = 0;
int sizeOfArray;
int decimalNumCopied;
printf("Please enter a number from 0 to 255: ");
scanf("%d", &decimalNum);
decimalNumCopied = decimalNum;
while(decimalNum != 0)//checking number of bits;
{
decimalNum = decimalNum / 2;
i++;
}
sizeOfArray = i;
//Trying to allocate just enough memory
binaryNum = (int*)malloc(sizeOfArray * sizeof(int));
while(decimalNumCopied != 0)
{
/*At next step I am trying to assign values to each element of the
array and it doesn't work
*/
binaryNum[i] = decimalNumCopied % 2;
decimalNumCopied = decimalNumCopied / 2;
i--;
}
for(i = 0; i <= sizeOfArray; i++)
{
printf("%d", binaryNum[i]);
if(binaryNum[i]== 0){zeroCounter++;}
}
printf("\nThere are %d zeroes", zeroCounter);
free(binaryNum);
return 0;
}