7

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?

Suraj
  • 932
  • 5
  • 23
  • 43
  • 1
    g++ extension: https://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Variable-Length.html#Variable-Length – yizzlez Aug 24 '14 at 17:16
  • 2
    It is not standards compliant C++. It is a compiler extension. You can set the compiler flags to be more strict about compliance (`-std=c++11` or `-std=c++98`.) – juanchopanza Aug 24 '14 at 17:16

2 Answers2

6
  1. Correct, you have discovered a 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.
  2. Yes, the code is correct, assuming that you are fine with using non-portable extensions to the language.
  3. This is true about standard-compliant compilers. You can tell 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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 2
    It's not in C++14, either. I believe they're waiting on an acceptable library wrapper now because `std::dynarray` failed. – chris Aug 24 '14 at 17:43
  • Not in C++17 or 20, either. About 3: gcc will still happily compile variable length arrays, even when specifying `-std=c++11` or any other version. If you add `-pedantic`, it will issue a warning, and with `-pedantic-errors` it will not compile. – He3lixxx May 29 '21 at 23:10
1

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.

This depends on what you mean by dynamic.

From a strictly technical perspective, in the context of the lifetime of an object, dynamic means something with dynamic storage duration. A storage duration is how long an object will live after it has been created. An object that has dynamic storage duration will continue to live on until it is explicitly destroyed. (Note that this explicit destruction may be obfuscated through the use of smart pointers such as std::unique_ptr)

However this does not seem to be what you're really asking about in this question. You seem to be asking:

If I want to create a container for objects, but I don't know how big that container needs to be until runtime, is new and malloc my only choice?

The answer to that question is no. And in fact, in modern C++ using new should be a choice of last resort, and using malloc should be even more last-resort than that.

Instead of trying to create a C-style array of N elements, use a vector instead:

std::vector <int> myInts;
for (int i = 0; i < 10; ++i)
  myInts.push_back (i);

This has several advantages:

  1. You don't have to delete anything
  2. You don't have to know how many elements will be put in to the vector before you create the vector -- just keep adding elements until you're done
  3. vector is guaranteed to have contigious storage, meaning the elements can be accessed using operator[] just like a C-style array
John Dibling
  • 99,718
  • 31
  • 186
  • 324
  • What do you mean by contiguous? As in, the elements of `vector` are always in series in the memory? Or by that you mean a `vector` element points to the next `vector` element and `[]` notation is used to access its elements. In latter, the elements might not be contiguous in the memory. – Suraj Aug 26 '14 at 13:26
  • @SurajThapar: Contigious as in in series in memory. – John Dibling Aug 26 '14 at 15:54
  • Well that sounds wrong. Memory Chunks/Memory = [░░▓▓░▓▓░░░▓░░▓░▓▓] , ▓ = Unavailable space, ░ = Free memory. Where each chunk represents ``'s size. Suppose if `vector` decides to keep the first element in the left most free memory, it will only be able to store 2 elements. As you said that one *doesn't have to know how many elements will be put into the `vector` before you create it*. So it will have to break the statement [3] i.e, contiguous storage (as in in series in memory) for it to avoid overflow. – Suraj Aug 26 '14 at 16:47
  • 1
    @SurajThapar: Right, `vector` manages the memory for you. If you `push_back` something and there isn't enough `capacity`, `vector` will reallocate and move your elements to new space. I promise -- the Standard **guarantees** that `vector` sores it's elements in contigious memory. – John Dibling Aug 26 '14 at 17:07