1

If I have a function, say, as follows:

int fun(int n,int a[n][n]){......}

Where n is some value I get from the user via standard input runtime. Am I allowed to use the n in [] for defining a[n][n]?

This seems to work in C but not in C++. What is an alternative if I want the exact same functionality in C++?(i.e. take an input as parameter, and the 2D array size itself should be dependent on this parameter)

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
hjbjnjn
  • 11
  • 1
  • 1
    C++ doesn't have variable sized arrays. [I recommend using `std::vector`](https://en.cppreference.com/w/cpp/container/vector). To get a 2D-like `vector`, [do something like this](https://stackoverflow.com/a/2076668/4581301). – user4581301 Oct 11 '19 at 20:49
  • 2
    It is allowed in C99 only (and, from memory, deprecated and removed from subsequent C standards). It has never been allowed in C++. In C++, use a standard container (say, `std::vector >`) which has the advantage that the container itself has information about its own number of elements (i.e. `n` doesn't need to be passed separately). – Peter Oct 11 '19 at 20:53
  • Son of a gun. I knew C99 added VLA, but I didn't know you could pass the array size in along with the array. Neat. – user4581301 Oct 11 '19 at 20:58
  • VLAs weren't removed from C11, but they were made optional. From what I gather, this is partly because few compilers actually bothered to implement them from C99. – Ben S. Oct 12 '19 at 04:29
  • Welcome to Stack Overflow! Raw C arrays are generally not recommended in C++. Please also show the caller code. – L. F. Oct 12 '19 at 10:32

0 Answers0