Xenheart
Xenheart

Reputation: 65

Array Length, why can't it be used when taking from command lines?

I'm trying to get one of my argv's (which is an int sent in as a string), to become the length of an array, but the compiler keeps telling at me that num_of _players isn't constant and cant be used.
Any suggestions why?

#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
    int num_of_players = stoi(argv[argc - 1]);
    int player_list[num_of_players];

    return 0;
}

Upvotes: 0

Views: 75

Answers (2)

Galik
Galik

Reputation: 48625

The problem is that declaring arrays in that way requires the size to be provided at compile time. They can not be declared with a value discovered at runtime.

The most basic alternative is to use a dynamic array which you can create manually:

#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
    int num_of_players = stoi(argv[argc - 1]);
    int* player_list = new int[num_of_players];

    // do stuff with player_list here...

    delete[] player_list; // REMEMBER to delete[] it!!

    return 0;
}

When you create something (like an array) using new or new[] you have to manually dispose of them (incl. give the memory back) using delete or delete[] respectively. However this can be forgotten so it is a potential source of memory leaks. For that reason one would typically use a type that manages the dynamic array automagically like a std::vector.

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

Because it isn't constant and can't be used.

Like how the size of an int is baked into your program, so is the size of an array. It has 3 elements, or 9 elements, or 512 elements … but this information cannot come from the command-line because it already had to be baked into your program when you compiled it.

Instead, use a "dynamic array" like std::vector that can grow and shrink as needed at runtime.

Upvotes: 3

Related Questions