When I first learned about dynamically allocated arrays in school, I always thought we used them for passing arrays as parameters to functions. But the more I have been practicing coding, I see now that normal arrays can be passed as parameters to functions. So guys what is the advantage? Why do we even need them?
say you want to allow the user the ability to enter detail about his students. You are not going to know when you compile the program how many students the user will have, thus you would do something like:
1 2 3 4 5 6 7 8 9
int main() {
int N;
std::cout<<"How many students do you have? ";
std::cin>>N;
student *student_array=new student[N];
//do stuff with student_array
delete[] student_array;
return(0);
}
But you could also do the same without allocating it dynamically
1 2 3 4 5 6 7 8 9
int main() {
int N;
std::cout<<"How many students do you have? ";
std::cin>>N;
student student_array[N];
//do stuff with student_array
delete[] student_array;
return(0);
}
@Smac89
Creating an array on the stack with non-constant size is only valid on some compilers (gcc with extensions enabled), also you can't call delete[] on a static array.