Advantage of dynamically allocated arrays

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?
So guys what is the advantage?
Being able to allocate dynamically. If you don't know the size needed for an array until runtime, you need to allocate it dynamically.
what naraku said.

usually arrays need to have a size when you create them. if you don't know the size or want to set it later, you need dynamically allocated arrays.

or just use vectors.
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);
}
Last edited on
@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.
If you use standard C use malloc()
The C++ standard way is:

int n=32;
std::vector<double> A(n);

Syntax: A[n] works on many compilers but I don't know what exactly do.
Last edited on
Topic archived. No new replies allowed.