0

I'm trying to understand why we have to use new operator in C++. I have wrote short program:

int N;
std::cin >> N;
int tab[N];

for (int i = 0; i < N; i++)
 tab[i] = i + 1;

for (int i = 0; i < N; i++)
 std::cout << "tab[" << i << "] = " << tab[i] << std::endl;

This program works correctly. The same behavior I have noticed in C using this algorithm (instead of malloc() function).

Benek
  • 91
  • 11
  • 2
    Try it with a larger N. Say 100 million... – Mysticial May 14 '14 at 18:30
  • 1
    Well... the name of this website says it all – TerraOrbis May 14 '14 at 18:31
  • 1
    @Brian It's really not though. This question is about variable-length arrays - the linked duplicate isn't. – sepp2k May 14 '14 at 18:32
  • @sepp2k aha, didn't catch that. I'll vote to reopen. – Brian Bi May 14 '14 at 18:34
  • In most C++ code that *you write* you will not (and probably should not) use `operator new` at all really. That doesn't mean that dynamic allocation is unnecessary, far from it. Sometimes you don't know how much memory you will need. Sometimes you need more than the stack will allow. Sometimes you need the allocation to persist across function calls. – Ed S. May 14 '14 at 18:39

2 Answers2

5

You're using a variable length array, which is not available in standard C++. It is part of C99, however, and some C++ compilers provide it as an extension. See Why aren't variable-length arrays part of the C++ standard?.

To get similar behavior in standard C++, or to use larger arrays than stack space would allow, you must use new[].

Of course, it's an even better idea to use standard library containers, such as std::vector, which manage the memory for you.

Community
  • 1
  • 1
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
1

Your example is not valid C++ code. If it compiles with your compiler, that must be because your compiler supports variable-length arrays as an extension to the language. If you compile in standard-compliant mode, you should get an error. So you need new[] to create arrays of variable size when you want to write standard compliant code.

You also need it if you want the array to live longer than the lifetime of the current function or if you don't want its size to be limited by the available stack space.

sepp2k
  • 363,768
  • 54
  • 674
  • 675