The question is the need for the operator new. It is intended for dynamic memory allocation, that is, during program execution, when the required size is unknown. But the following simple example was compiled and worked for me (although it showed garbage).

#include <iostream> using namespace std; int main(){ int size; cin >> size; int A[size]; for(int i = 0; i < size; i++) cout << A[i] << " "; return 0; } 

So the question arose, what happens in this example and is it correct at all? How is memory allocated? In what cases do you need the new operator, and without it it would be enough?

What is the difference between this array definition and this (besides garbage):

 int *A = new int[size]; 
  • five
    As far as I remember, this code should not compile at all - arrays with non-constant sizes are allowed by the C standard, but not C ++. Specialists, correct me if I'm wrong ... - Harry
  • Nichche do not understand 0_o ... agree with @Harry ... but it works! - Majestio
  • @Majestio G ++ extension? - Harry
  • @Harry, nenay ... clang is also a compilation of ¯ \ _ (ツ) _ / ¯ - Majestio
  • @Harry, here it is - gcc.gnu.org/onlinedocs/gcc/Variable-Length.html - Majestio

5 answers 5

From the point of view of the standard C ++, this code fragment

 int size; cin >> size; int A[size]; 

is incorrect. The C ++ standard does not allow variable-length arrays. The size of the array must be a constant value, known at compile time, unless it is a declaration of the array with external binding.

However, some compilers introduce their own language extensions, which sometimes contradict the standard. And it looks like you have compiled this code with a compiler that has this extension.

This array has an automatic memory duration, which is usually limited, and therefore does not allow to determine arrays of large sizes. Declaring large arrays in this memory can lead to the fact that other objects can not be defined, and the program will crash.

Difference between these ads

 int A[size]; int *A = new int[size]; 

is that, as already stated, the first ad is incorrect. In the first sentence, an array is declared that has an automatic memory duration, while in the second case, a pointer is declared with an automatic memory duration and an unnamed array with dynamic memory duration. This means that the variable A , can cease to exist, and the array will continue to exist. In the first case, the compiler is responsible for allocating memory, and it frees it automatically, while in the second case, the user is directly responsible for allocating memory and freeing it.

  • ideone this code (tc-a code) “swallowed”, I am surprised ... - Majestio
  • @Majestio ideone does not show warnings if there were no errors. Try another site . - αλεχολυτ

There are 3 types of memory.
1 Stacked - it is allocated for variables in the scope of the function.

 int setArray() { int A [5]; } 

in this case, an array with 5 cells is allocated. 5 is a constant! This type of recording is not acceptable:

 int setArray() { int length = 5; int A [length]; } 

and here it is possible

 int setArray() { const int length = 5; int A [length]; } 

That is, the memory is allocated to the compilation stage.

2 Static memory is allocated before the program starts, at the stage of compilation and assembly. Static variables have a fixed address, known prior to the launch of the program and not changing during its operation. Record:

 static int A [5]; 

A will be available not only in the scope of the function

3 Pile (Dynamic Memory). Stand out in the process of the program. That is, you do not know which array you have - 5 elements or 10. In this case, you need to allocate dynamic memory.

 int *A = new int[size]; 

After working with an array (object, etc.), it is necessary to clear it:

 delete [] A; 
  • one
    memory is allocated before the compilation stage // and maybe even before the code is written? Also forgot about thread storage duration . - αλεχολυτ

Here you have a dynamic array on the stack. The problem is that in general the stack is small and you cannot create a large array on it. Well, the array on the stack will be destroyed when exiting the function.

It is best to use std :: vector as a dynamic array in C ++.

  • So this way you can not dynamically allocate memory? Why then does language allow it? - Antosha19955
  • I asked a "cunning" question))) Something in the "Danish kingdom has changed") It remains to find out. - Majestio
  • one
    @ Antosha19955 s ++ allows a lot of things. But this does not mean that it will work exactly the way you came up with yourself and that it was generally conceived :) - KoVadim
  1. This example is incorrect, since in C ++ you can only specify the size of the array as a constant. For example:

     const int size = 3; int A[size]; 

    or

     int A[3]; 
  2. The difference of creating an array in the aforementioned way from this method is int *A = new int[size]; is that in the second case the size variable may not be a constant, that is, you can read it from the keyboard. And then you can work with this array as usual. That is, to get any element, use the following construction: A[n] .

  3. The new operator is needed for dynamic memory allocation. For a deeper understanding of the topic of your question, I recommend reading the information on this site: http://cppstudio.com/post/432/

    The proposal to introduce arrays with the runtime size into the C ++ language (a remote analogue of the VLA in C99) existed at the intermediate stages of the development of the C ++ 11 standard and is easily found in draft versions of the document. However, none of this was included in the final version of the document and the topic of arrays with the runtime size in C ++ was closed.

    Nevertheless, many compilers either already had a more or less relevant draft implementation of such functionality, or rushed to implement it even before the release of the final version of C ++ 11. It is these implementations of this functionality that continue to live in some compilers as an extension of the language.

    Do not forget that the “example compiled” is in no way a confirmation of the correctness of the code from the point of view of the C ++ language. When using the GCC / Clang compilers, make it a habit to always use the -pedantic-errors parameter to cleanse these implementations from the motley student initiative.

    In what cases do you need the new operator

    The new operator is primarily needed for unlimited manual control over the lifetime of the objects you manually create. Objects created through new live "forever", i.e. until you destroy them yourself via delete or until your program terminates. Their lifetime is not tied to the boundaries of local blocks.

    Also, new needed to select at run-time a specific type of created objects (as in the case of polymorphic classes) and / or their number (in particular, in the case of arrays, this is the size of the array). This can be achieved only by means of dynamic creation of objects.

    Much of this can be achieved without new or other variants of dynamic memory allocation, and only competently / cleverly organizing local definitions of objects, but in the general case it will not be possible to overcome the limitations of the lifetime (and there is no point in it).

    What is the difference between this array definition and such (besides garbage)

    (It's not at all clear what kind of "garbage" you are talking about).

    The difference in the first place is that the local array will be automatically destroyed upon completion of the block containing its declaration. And the array created through new[] will not be automatically destroyed at all - it will live until it is destroyed by delete[] .

    • 2
      GCC / Clang make it a habit to always use the -pedantic-errors parameter to clean these implementations from the motley student initiative. Studio komiplyator this also applies. - KoVadim