Allocating arrays in C++ -


when started programming c++ learned allocate array size using dynamic memory allocation follows:

int main() {     int narraylength;      cout << "enter array length: ";     cin  >> narraylength;      int *narray = new int[narraylength];      // contents      delete[] narray;      return 0; } 

now tried following code using code::blocks 12.11 mingw32-g++ // gnu gcc compiler.

int main() {     int narraylength;      cout << "enter array length: ";     cin  >> narraylength;      int narray[narraylength];      return 0; } 

this works fine.

therefore, why should use dynamic memory allocation in case when easier method works fine?

you should use neither.

the first valid, it's c-style code. second non-standard code - it's accepted compiler because of extension.

use std::vector instead:

#include <vector> int main() {     int narraylength;      cout << "enter array length: ";     cin  >> narraylength;      std::vector<int> narray(narraylength);      return 0; } 

a vector has same semantics array, can grow dynamically (and automatically), , pesky memory management under hood.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -