How to pass size of an array from command line

Is there any way to pass the size of an array using a command prompt.


1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
	//const int SIZE = 5;
	
	int arr[ argv[1] ];
	
	return 0;
}
Last edited on
Well you can use
SIZE = atoi( argv[1] );
where atoi() is declared in <cstdlib>

However, you shouldn't set the size of a standard array with anything that isn't known at compile time (though some compilers permit it). You should use either a dynamic array, created with new, or let the compiler do the memory management and use a vector<int>.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <cstdlib>
#include <vector>

using namespace std;

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        cout << "Missing size parameter\n";
        return 1;
    }
    int size = atoi(argv[1]);
    if (size <= 0)
    {
        cout << "size " << argv[1] << " must be greater than zero\n";
        return 1;
    }
    
    // C++ recommended way - use vector
    vector<int> array1(size);
    
    
    // Possible alternative, but not recommended - use new[] and delete []
    int * array2 = new int[size];

    /*
        Code which uses the array
        goes here
    */
    
    
    // Before exit, de-allocate array2
    delete [] array2;
    
    return 0;
}
Is it possible to fix this errors

error: ‘len’ was not declared in this scope
error: ‘arr’ was not declared in this scope

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
 
using namespace std;
 
class cls 
{
	private:
		int arr[len];
		
	public:
		int len;
		void print_arr();
};
 
int main(int argc, char *argv[])
{
	cls obj;
	obj.len = atoi( argv[1] );
	obj.print_arr();
	
	return 0;
}
 
void cls::print_arr()
{
	for (int i = 0; i < len; i++)
	{
		arr[i] = i;
		cout << arr[i] << " ";
	}
} 
Last edited on
Your code at line 8
 
	int arr[len];

is not possible in standard C++, because len is not a compile-time constant. It may be allowed by your compiler, but could fail if a different compiler is used. It is best not to rely on such quirks, especially when learning. Use a vector, or maybe new [] and delete[].
Registered users can post here. Sign in or register to post.