I used to believe that for stack allocated arrays, its size has to be defined at compile time. I always use either std::vector
or the new[]
operator if the size of the array is not known beforehand.
However, recently I came across C++ code which compiled and executed fine even when the size of the array was not known at compile time. I've gone through a similar question on this but I've still not got the clarity in my mind on this.
I tried the following code online at cpp.sh. I don't understand the output I'm getting.
Code
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<endl<<"Enter the size of arr1: ";
cin>>n;
int arr1[n];
cout<<endl<<"Enter the elements of arr1 below"<<endl;
for(int i=0;i<n;++i)
cin>>arr1[i];
cout<<endl<<"Size of arr1: "<<sizeof(arr1)/sizeof(arr1[0]);
cout<<endl<<"sizeof(arr1): "<<sizeof(arr1);
cout<<endl<<"sizeof(arr1[0]): "<<sizeof(arr1[0])<<endl;
int arr2[3];
cout<<endl<<"Size of arr2: "<<sizeof(arr2)/sizeof(arr2[0]);
cout<<endl<<"sizeof(arr2): "<<sizeof(arr2);
cout<<endl<<"sizeof(arr2[0]): "<<sizeof(arr2[0])<<endl;
return 0;
}
Output
Enter the size of arr1: 3
Enter the elements of arr1 below
1 3 5
Size of arr1: 0
sizeof(arr1): 1
sizeof(arr1[0]): 4
Size of arr2: 3
sizeof(arr2): 12
sizeof(arr2[0]): 4
If it's not valid in C++, why does it even compile? And how is it that I can take 3 integers as input in arr1 but it's size is 1?