【问题标题】:Invalid conversion from char * to int fpermissive从 char * 到 int fpermissive 的无效转换
【发布时间】:2019-09-22 12:40:38
【问题描述】:
#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;
}

当我尝试运行此代码 sn-p 时,我收到一个错误invalid conversion from char * to int fpermissive。我不知道这个错误是什么意思。如果有人有任何想法,请帮我找出它的含义。

提前谢谢你。

【问题讨论】:

  • n = argv[0] 正在将 char * 转换为 int。标准库中有各种用于将字符串转换为整数值的函数。即使使用这些函数,您的代码也没有意义 - argv[0] 将是一个代表程序名称的字符串,因此将其转换为 int 没有意义。 delete stuff 也应该是 delete [] stuff 以避免未定义的行为。

标签: c++ pointers char int


【解决方案1】:

argv 是一个指向一个字符的指针,简而言之,您可以将其假定为指向字符串的指针,并将其中的一个元素直接分配给 n。

n 是一个字符数组。 首先通过 atoi() 将 n 转换为整数,您可以在 stdlib.h 中找到它

我猜在 C++ 中它是 cstdlib。

【讨论】:

    【解决方案2】:

    你不能分配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)等。

    此外,如果用户在未输入命令行参数的情况下运行您的应用程序,则您不会初始化 n。并且第一个用户输入的参数存储在argv[1]argv[0] 包含调用应用程序的路径/文件名。

    另外,您需要使用delete[] 而不是delete。经验法则 - 一起使用 newdelete,以及一起使用 new[]delete[]。或者更喜欢根本不直接使用它们(改用std::vectorstd::make_unique&lt;T[]&gt;() 等)。

    试试这样的:

    #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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      相关资源
      最近更新 更多