You can't assign a char* pointer to an
intvariable, unless you type-cast it, which is not what you need in this situation. You need to parse the
char*string using a function that interprets the *content* of the string and returns a translated integer, such as [
std::atoi()](https://en.cppreference.com/w/cpp/string/byte/atoi), [
std::stoi()`](https://en.cppreference.com/w/cpp/string/basic_string/stol), etc.
Also, you are not initializing n
if the user runs your app without entering a command-line parameter. And the first user-entered parameter is stored in argv[1]
, argv[0]
contains the calling app's path/filename instead.
Also, you need to use delete[]
instead of delete
. Rule of thumb - use new
and delete
together, and new[]
and delete[]
together. Or prefer to not use them directly at all (use std::vector
, std::make_unique<T[]>()
, etc instead).
Try something more like this:
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
int main(int argc,char** argv){
int n = 0; // <-- initialize your variables!
if (argc > 1)
n = atoi(argv[1]); // <-- [1] instead of [0]! and parse the string...
int* stuff = new int[n];
vector<int> v(100000);
delete[] stuff; // <-- use delete[] instead of delete!
return 0;
}
n = argv[0]
is converting achar *
to anint
. There are various functions in the standard library for converting strings to integral values. Even with those functions, your code doesn't make sense -argv[0]
will be a string that represents the name of your program, so converting it to anint
doesn't make sense. Alsodelete stuff
should bedelete [] stuff
to avoid undefined behaviour. – Peter