'Invalid conversion from char * to int fpermissive

#include<iostream>
#include<vector>
using namespace std;

int main(int argc,char** argv){
int n;
if(argc>1)
    n=argv[0];
int* stuff=new int[n];
vector<int> v(100000);
delete stuff;
return 0;
}

When I try to run this code snippet I got an error invalid conversion from char * to int fpermissive. I can not figure out what does this error indicate. If any one have any idea please help me to find out its meaning.

Thank you in advance.



Solution 1:[1]

argv is a pointer to a pointer to a character which in short you can assume as pointer to strings and you assign an element of that directly to n.

n is a character array. First convert n to an integer by atoi() which you can find in stdlib.h

I guess in C++ it is cstdlib.

Solution 2:[2]

You can't assign a char* pointer to anintvariable, unless you type-cast it, which is not what you need in this situation. You need to parse thechar*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;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sahil
Solution 2