I've made program that changes decimal number into binary. It works fine if I put smaller number for example 55,10,22 but as soon as I put in a number like 100, 999,523 program will stop working. I am asking for explanation if possible.
Thank you for reading!
#include <iostream>
usingnamespace std;
int main()
{
int number;
int l = 0;
int dvojiski [l];
cout << "Enter decimal number :" ;
cin >> number;
while(number > 0) {
dvojiski [l] = number % 2;
number = number / 2;
l++;
}
int s = l - 1;
for (int x = 0;x < l;x++){
cout << dvojiski[s] << endl;
s--;
}
}
Your program doesn't work for smaller numbers. It just appears to.
Firstly, line 11 is illegal C++. The size of an array must be a compile time constant. Secondly, were it legal, changing the value of l after the definition of dvojiski would not change the size of dvojiski and since its size is 0, meaning it has no valid elements, you have no business pretending it does.
In other words, you are clobbering memory that you don't own.
Your second statement " Secondly, were it legal, changing the value of l after the definition of dvojiski would not change the size of dvojiski and since its size is 0, meaning it has no valid elements, you have no business pretending it does." I kinda don't understand. Could you make simple example? Tho if you don't want or don't have time It's fine!
int array[size];
// If we were able to change size here, it would not change the amount of
// elements held in array. That is determined at array's definition.