简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM