I am writing a program to get all the prime nos upto a number n(input).
Now in this program, I have used static storage allocation int arr[n+1]
however my compiler doesn't know the value of n during compilation (n
is provided by the user as input) and hence doesn't know how much space should be allocated.
Should one use dynamic storage allocation in this program?
int *arr=new int[n+1]
However, the program is running perfectly in both cases.
I just wanted to know why my program is running fine in case of static storage allocation even though n
is unknown during compilation and the compiler doesn't know how much storage should be allocated.
void prime(int n) {
int arr[n + 1]; // <=======
for (int i = 0; i < n + 1; i++) {
arr[i] = 1;
}
for (int i = 2; i <= n; i++) {
for (int j = 2 * i, l = 0; j < n + 1; j = (2 + l) * i, l++) {
arr[j] = 0;
}
}
for (int i = 2; i < n + 1; i++) {
if (arr[i] == 1) {
cout << i << " ";
}
}
}
int main() {
int n;
cin >> n;
prime(n);
}