I'm new to C++ and this is a very basic question.
In C++ there are only two ways to create dynamic arrays (read in a book, correct me if I'm wrong) using memory allocation either by new
operator or malloc()
function which is taken from C.
When declaring an array int array[size]
, the square brackets []
must have a const
.
However in the following code size
is an unsigned int
variable.
#include<iostream>
int main() {
using namespace std;
unsigned int size;
cout<<"Enter size of the array : ";
cin>>size;
int array[size]; // Dynamically Allocating Memory
cout<<"\nEnter the elements of the array\n";
// Reading Elements
for (int i = 0; i < size; i++) {
cout<<" :";
cin>>array[i];
}
// Displaying Elements
cout<<"\nThere are total "<<size<<" elements, as listed below.";
for (int j = 0; j < size; j++) {
cout<<endl<<array[j];
}
return 0;
}
While compiling g++ throws no error and moreover the program runs perfectly.
Question 1 : Could this be another way to create dynamic array?
Question 2 : Is the code correct?
Question 3 : If []
can only contain const
, why does the code work?
We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.
If you don't delete them, they will remain there (but won't be accessible -> this is called memory leak) until your process exits, when the operating system will deallocate them. Save this answer.
You can declare an array without a size specifier for the leftmost dimension in multiples cases: as a global variable with extern class storage (the array is defined elsewhere), as a function parameter: int main(int argc, char *argv[]) . In this case the size specified for the leftmost dimension is ignored anyway.
In C++, we can create a dynamic array using the new keyword. The number of items to be allocated is specified within a pair of square brackets.
gcc
extension. This has been allowed in C for a long time, but it has not made it into C++ standard until the C++14.gcc
that you do not want to use extensions by supplying a -std=c++98
or -std=c++11
compiler flag.If you need a dynamically-sized array in C++, a better approach would be to use std::vector<T>
. It gives you the flexibility of dynamically allocated array, and takes care of managing the allocated memory for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With