Advantage of dynamically allocated arrays

Jan 23, 2013 at 5:34am
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?
Jan 23, 2013 at 6:37am
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.
Jan 23, 2013 at 7:32am
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.
Jan 23, 2013 at 2:36pm
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);
}
Jan 24, 2013 at 7:33pm
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 Jan 24, 2013 at 7:34pm
Jan 24, 2013 at 7:37pm
@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.
Jan 25, 2013 at 4:18pm
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 Jan 25, 2013 at 4:19pm
Topic archived. No new replies allowed.