Standard C++ does not support the variable length arrays (VLAs) of C99 and g++.
In standard C++ you can use e.g. std::vector
, like this (your code modified):
#include <iostream>
#include <vector>
int main(){
int sz;
std::cout<<"number?\n";
std::cin>>sz;
// This line
std::vector<double> dynamic_arr( sz ); // Initialized to zeroes.
//output the value just to use the array.
std::cout<<dynamic_arr[0]<<std::endl;
}
Also, for strings you can use std::basic_string
, usually via the typedef
s std::string
and std::wstring
.
Generally the main problem is just the dynamic size, as above, and then std::vector
and std::basic_string
do the job nicely. However, sometimes the problem is efficiency, how to do extremely efficient stack allocation of a dynamic size array. Many C and C++ implementations support the non-standard function alloca
for that, but unfortunately they differ greatly in how it handles failures. As far as I know there is no commonly available library solution for that either. But happily, the main usage that I know of (even though as mentioned alloca
is available for a number of platforms) has been for string encoding translation in Windows, and that's less and less relevant as time goes on and Windows programs more and more are pure Unicode-oriented.