Why do I need dynamic memory allocation if I can just create an array? [duplicate]
Asked Answered
D

2

6

I was reading about dynamic memory allocation and static memory allocation and found the following about dynamic memory allocation:

In the programs seen in previous chapters, all memory needs were determined before program execution by defining the variables needed. But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input.

So I wrote the following program in C++:

#include <iostream>

int main()
{
  int n = 0;
  int i = 0;

  std::cout << "Enter size: ";
  std::cin >> n;
  int vector[n];

  for (i=0; i<n; i++)
  {
    vector[i] = i;
  }

  return 0;
}

This program works. I don't understand how it works. When is the size determined here? How does the vector get allocated in this case?

Diffusivity answered 13/12, 2018 at 10:50 Comment(2)
The code above is not legal according to C++ standard. Compilers sometimes accept code that is not legal.Samp
I must say that the question you ask in the title is quite different from the once you ask in the body of the post.Nester
O
8

According to this (emphasis mine):

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.

Note that this is just an extension and won't work on every compiler, for instance it doesn't work for me in MSVC (I get the error "expression must have a constant value").

Owe answered 13/12, 2018 at 10:53 Comment(1)
Also, the prohibition against variable bounds is not the only reason to dynamically allocate a thing. Lifetime and ownership are also big parts of the decision.Amandaamandi
M
-2

Above Code Will Generate error in latest version of compiler.This Code will Work in old version of DOSBOX.

Array's Size Must be Constant Integer.

So you can define it using two ways

1.#define Macron

#include<iostream>
#define n 5

main() {
   ...
      ...
      int array[n];
}

2.const keyword

#include<iostream>
....
main() {
   int x;
   cout << "Enter Size Of Array";
   cin >> x;

   const int n = x;

   int array[n];
   ...
      ...
}
Muscid answered 13/12, 2018 at 12:6 Comment(3)
This doesn't make it valid: const int n = x; That value still depends on a run-time value, so is not a compile-time constant and not a valid array bound. Defining the size as a "Macron" doesn't help, the value needs to be read from the user.Fortress
It doesn`t work I got "expression must have a constant value"Gunlock
it is working for me . I compiled program using g++ commandMuscid

© 2022 - 2024 — McMap. All rights reserved.