当我运行命令行./hello.out时,核心将被丢弃。有人可以告诉我我缺少什么。
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int counter = 1, sum = 0,x;
x= atoi(argv[1]);
if (x<0)
{cout << "Errorn"; exit(1);}
if (argc !=2)
{cout << "Errorn"; exit(1);}
while (counter <= x)
{
cout << counter << endl;
sum = sum + counter;
++counter;
}
cout << "Sum is " << sum << endl;
return 0;
}
看来,您正在尝试访问不存在的argv
的元素,因此您正在访问程序无法控制的内存。当您这样做时,内核将立即杀死您的程序。您正在检查argc
的值,这是正确的事情,但是在访问argv
之后,您要这样做。您只需要在访问argv
之前执行该检查。
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int counter = 1, sum = 0,x;
if (argc !=2) argv // <-- Make sure there are two elements before indexing into
{
cout << "Errorn";
exit(1);
}
x = atoi(argv[1]); // <-- You should study and use 'std::stoi' instead
if ( x < 0 )
{
cout << "Errorn";
exit(1);
}
while (counter <= x)
{
cout << counter << endl;
sum = sum + counter;
++counter;
}
cout << "Sum is " << sum << endl;
return 0;
}
好....在第6行上您访问argv [1],但是您尚未通过任何派托者...所以argv [1]可以指向任何地方