-1

in which cases should I use the keyword new to allocate array when the size is a variable? I am reading this code: https://github.com/Hawstein/cracking-the-coding-interview/blob/master/1.7.cpp

In the function zero(), why row[m] and col[n] declarations doesn't cause errors? The m and n are function variables.

Thanks

fast tooth
  • 2,317
  • 4
  • 25
  • 34

2 Answers2

2

VLA - variable length arrays are a nonstandard extension of the C++ language, thus your code can only be compiled with a compiler extension

You should use dynamic allocated memory in every case when you don't know in advance the size of the array and you don't want/can't waste precious stack memory allocating a temporary or, even better if that works for you, use a std::vector (a vector uses heap memory anyway for its elements)

Edit: Another important suggestion is to take a look at smart pointers which can often offer additional advantages over raw pointers

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246
  • I have one more question. if I new something within a function and return its pointer. Is the returned pointer a ghost one? Is something created by new, will only be freed by the keyword delete? Thanks – fast tooth Sep 14 '14 at 21:12
  • I recommend a smart pointer for such operations since it frees you from the hassle of having to free memory when it goes out of scope (plus other advantages). Anyway, yes: the book-keeping is your duty with `new` – Marco A. Sep 14 '14 at 21:13
0

Never.

Modern c++ compilers can handle variables for array sizes. They just use the values currently in m and n. There is no need to use new.

Louis Newstrom
  • 172
  • 1
  • 1
  • 13
  • The only time you need to use `new` is if you need to have a variable whose scope is not local. In other words, only if you need to either 1) delete the variable before the function exits or 2) keep the variable around after the function exits. – Louis Newstrom Sep 14 '14 at 21:12
  • 2
    Just because some compilers can handle them (without certain flags that people like me use during compilation) doesn't make them portable or standard. – chris Sep 14 '14 at 21:14