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.
#include using namespace std;
int main(int argc, char *argv[])
{
//const int SIZE = 5;int arr\[ argv\[1\] \]; return 0;
}
-
Arguments come as an array of char * - that's the argv variable. One way to convert them is :
int size = atoi( argv[1] );
Now consider this code
#include
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] << " ";
}
}Getting errors error: ‘len’ was not declared in this scope error: ‘arr’ was not declared in this scope
-
Now consider this code
#include
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] << " ";
}
}Getting errors error: ‘len’ was not declared in this scope error: ‘arr’ was not declared in this scope
The array needs to be dynamically allocated. This is done using the new operator. I usually prepend an "m_" to member variable names so I know that is what they are. The array will be allocated in the class constructor and released in the destructor.
class cls
{
private:
int * m_array;public:
int m_length;cls( int length ); // constructor ~cls(); // destructor void print\_array();
};
cls::cls( int length ) // constructor
{
m_length = length;
m_array = new int[length];
}cls::~cls() // destructor
{
delete [] m_array;
m_array = nullptr;
}int main(int argc, char *argv[])
{
int length = atoi( argv[1] );
cls obj( length );
obj.print_array();
return 0;
} -
The array needs to be dynamically allocated. This is done using the new operator. I usually prepend an "m_" to member variable names so I know that is what they are. The array will be allocated in the class constructor and released in the destructor.
class cls
{
private:
int * m_array;public:
int m_length;cls( int length ); // constructor ~cls(); // destructor void print\_array();
};
cls::cls( int length ) // constructor
{
m_length = length;
m_array = new int[length];
}cls::~cls() // destructor
{
delete [] m_array;
m_array = nullptr;
}int main(int argc, char *argv[])
{
int length = atoi( argv[1] );
cls obj( length );
obj.print_array();
return 0;
} -
Now consider this code
#include
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] << " ";
}
}Getting errors error: ‘len’ was not declared in this scope error: ‘arr’ was not declared in this scope