Is it possible to pass a variable length array as a parameter in C++?

Related searches

I do not know the value of V before. It is found within a file I open in the program. It cannot be defined as such #DEFINE V __. It does not work as a global variable. The input file changes V based on the contents. Expected the parameters to pass and use the djisktra's algorithm found on Geeks for Geeks.

I have tried declaring V globally, but I am given an error saying "variable must have constant value."

void dijkstra(int graph[V][V], int src, int V)
//array function being pasted, error is the V in graph[V]
//V is defined at beginning of main as 
int V;
//where V is changed
while(std::getline(file2,newstr))
{
    if(newstr.find(check) != std::string::npos)
    {
        V++;
    }
}
//where it is passed in main
for(int i = 0; i < V; i++)
{
    size = V;
    dijkstra(array[size][size], i, V);        
}

Don't use C-style arrays. Use std::vector and friends from the Standard Library where you can ask for the size if you want to know.

Converted:

void dijkstra(const std::vector<std::vector<int>>& graph, int src) {
  auto v = graph.size();

  // ... Other code.
}

For inserting you can use push_back:

std::vector<std::vector<int>> graph;

while(std::getline(file2,newstr)) {
  if(newstr.find(check) != std::string::npos) {
    std::vector<int> row;

    row.push_back(...);

    graph.push_back(row);
  }
}

Then pass it in like a regular variable:

dijkstra(graph, src);

If all that vector stuff looks really ugly, typedef it to something more friendly looking.

Passing Variable-Length Array to a Function, Are you really passing in a VLA to your function? And even if you are, you don't have to specify the size of an array that is passed into a function� Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. C supports variable sized arrays from C99 standard. For example, the below program compiles and runs fine in C. Also note that in C99 or C11 standards, there is feature called “flexible array members”, which works same as the above.

For c style arrays, you need to know the size at compile time. A variable like int N; is a runtime value. A variable like constexpr int N = 9; is usable at compile time and cannot be mutated.

If you need an array sizeable at runtime, you need some sort of dynamic array. The most common one is std::vector.

void dijkstra(std::vector<int> graph, int src, int V)
std::vector<int> graph;
graph.resize(V * V); // vector are resizable

for(int i = 0; i < V; i++)
{
    size = V;
    dijkstra(graph, i, V);        
}

Variable Length Arrays in C and C++, Recommended Posts: Variable Length Argument in C � Variable length arguments for Macros � Can we access global variable if there is a local� Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file. Use va_arg macro and va_list variable to access each item in argument list.

Is it possible to pass a variable length array as a parameter in C++.

No.

Variable length arrays are not supported in std C++, But read on, they have an alternative that is surprisingly better.


I do not know the value of V before it is found within a file I open in the program.

A 1d vector is trivial to create, after your code has found V, no compile time constant required.

Early in the startup in one of my programs, the gBoard vector is built using argv[3] and argv[4]. Here is a snippet:

  aTermPFN               += argv[1];    // ouput tty, /dev/pts/<argv[1]>
  fillPatternChoiceLetter = argv[2][0];
  aMaxRow                 = stoi(argv[3]);
  aMaxCol                 = stoi(argv[4]);
  userDim                 = true;

Clearly, the program has already started ... and V size is easily computed from (aMaxRow * aMaxCol).

I find it easy to access a 1d vector (or 1d array), in row major order, as if it is a 2d matrix, with the following function:

// game-board-index: computes index into the single dimension vector
//                   from 2d (row, col) matrix coordinates
size_t gbIndx(int r, int c) { return static_cast<size_t>((r * maxCol) + c); }

// a 2d game board of cells

// 2d access (row major order) implemented using 1d access
Cell_t*  getCell( int r, int c )   { return (gBoard [gbIndx(r,c)]); } 

// 1d access is surprisingly convenient for many functions
Cell_t*  getCell( uint gbIndex  )  { return (gBoard [gbIndex]);     } 

Sample initialization usage:

//              vvvvvvvvvvvvvvvvvvv_-- 2d matrix access
gBoard [ gbIndx((midRow+1), midCol)   ] -> setOptionX();
//       ^^^^^^--1d row-major order index 

A randomized gGoard is trivial in 1d:

void GOLUtil_t::setRandom() { CellVec_t myVec(gBoard); // copy cell vector

random_device rd; mt19937_64 gen(rd()); shuffle (myVec.begin(), myVec.end(), gen); // shuffle order

int count = 1; for ( auto it : myVec ) // randomly mark half the cells { if(count++ & 1) it->setAlive(); // every odd cell } }


Note from https://en.cppreference.com/w/cpp/container/vector:

"The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements. This means that a pointer to an element of a vector may be passed to any function that expects a pointer to an element of an array."


I was surprised how often the 1d access enabled simpler code.

for (auto it : gBoard)
   it->init();        // command each cell to init

Summary:

Despite variable-length-arrays (vla) not being supported in std C++, I believe you will find std::vector a better alternative. And you will find that passing the vector within your code works.

Passing Arrays as Function Arguments in C, Passing Arrays as Function Arguments in C - If you want to pass a function, you would have to declare a formal parameter in one of following three ways and all t. double getAverage(int arr[], int size) { int i; double avg; double sum = 0; for (i� Passing Arrays as Function Arguments in C - If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all t

Variable Length (Using the GNU Compiler Collection (GCC)), If you want to pass the array first and the length afterward, you can use a forward declaration in the parameter list—another GNU extension. The ' int len ' before the semicolon is a parameter forward declaration, and it serves the purpose of making the name len known when the declaration of data is parsed. How to dynamically allocate a 2D array in C? How to pass a 2D array as a parameter in C? How to write long strings in Multi-lines C/C++? What are the data types for which it is not possible to create an array? Variable Length Arrays in C and C++; A shorthand array notation in C for repeated values; Accessing array out of bounds in C/C++; strcpy

Variable-length array, In computer programming, a variable-length array (VLA), also called variable- sized, In C, the VLA is said to have a variably modified type that depends on a value (see In C99, the length parameter must come before the variable-length array Ada arrays carry their bounds with them, so there is no need to pass the� You can only do that in C99 variable-length arrays [code]void somefunc(int size) { int vla[size]; // do something with vla } // vla is automatically destroyed when out of scope [/code]Note that the array will be created on stack so you nee

The array notation in the prototype does not change anything. An array passed into a function is always passed by address, since the array's name IS a variable that stores its address (i.e. a pointer). Pass-by-address can be done in returns as well -- we can return the address of an array.

Comments
  • C++ does not have variable length arrays. Use std::vector
  • C++ does not have variable length arrays. C does, and some compilers provide them as an extension. Use std::vector.
  • "I do not know the value of V" it is 5, as I -> 1, V -> 5 X -> 10 ;-)
  • Using raw arrays is generally perfectly fine. Though in this case, one really should use a matrix-class. A vector-of-vector is decidedly sub-optimal.
  • @Deduplicator "Fine" is highly subjective here. C arrays have no intrinsic size, you need to pass in data + size pairs, and that can get ugly for multi-dimensional structures. Fully agreed, though, that a proper matrix class is better.
  • This answer contains a simple matrix class.
  • @user4581301 As a bonus that does 2D emulation, which is allows for a more compact structure with fewer pointers and potential memory fragmentation.