从 char * 到 int fpermissive 的无效转换

问题描述 投票:0回答:2
#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;
}

当我尝试运行此代码片段时,出现错误从 char * 到 int fpermissive 的无效转换。我无法弄清楚此错误表示什么。如果有人有任何想法,请帮助我找出它的含义。

提前谢谢你。

c++ pointers char int
2个回答
0
投票

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

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

我猜在 C++ 中它是 cstdlib。


0
投票

你不能分配一个

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
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), 等等

另外,如果用户在没有输入命令行参数的情况下运行您的应用程序,您就不会初始化

n
。并且第一个用户输入的参数存储在
argv[1]
中,
argv[0]
包含调用应用程序的路径/文件名。

此外,您需要使用

delete[]
而不是
delete
。经验法则 - 一起使用
new
delete
,以及
new[]
delete[]
一起使用。或者根本不想直接使用它们(使用
std::vector
std::make_unique<T[]>()
等代替)。

尝试更像这样的东西:

#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.