[英]Stoi and debugging using valgrind and gdb
so I am supposed to debug code that does not work and I am having issue on the line [x-1] = std::stoi(t);. 所以我应该调试不起作用的代码,并且在[x-1] = std :: stoi(t);行上遇到问题。 I know that I need to have c++ 11 compiler to work, which I do but it still is not working.
我知道我需要有c ++ 11编译器才能正常工作,但我仍然无法正常工作。 There's a possibility that something else is wrong, but I am not too sure.
可能还有其他问题,但是我不太确定。 Thanks in advance.
提前致谢。
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int * p;
/*
* * Return the sum of the n values in x starting at index 0.
* * Note: x is a pointer to an array of ints.
* * If x is null, then return -1.
* * If n is 0 and x is not null, then return 0.
* */
int sum(int * x, int n);
int main(int argc, char * argv[]){
int * x = new int[argc];
for(int i = 1; i < argc; i++){
string t (argv[i]);
x[i - 1] = std::stoi(t); //it says stoi is not a member of std
}
//int * p;
cout << "*x is " << (*x) << endl;
int y = sum(x, argc);
cout << "y is " << y << endl;
int z = sum(p, argc);
cout << "z is " << z << endl;
return EXIT_SUCCESS;
}
int sum(int * x, int n){
int sum;
for(int i = 0; i < n; i++){
sum = sum + x[i];
}
return sum;
}
~
The code compile fine with G++ 使用G ++可以很好地编译代码
g++ -std=c++11 main.cpp -o myApplication
Beside having a compiler which support c++11, did you remember to specify the standard from the compiler flag? 除了拥有支持c ++ 11的编译器外,您还记得从编译器标志中指定标准吗?
EXTRA: 额外:
your code then fails because: 1. you have no checks on NULL condition on sum input pointer. 然后,您的代码将失败,因为:1.您没有对总和输入指针上的NULL条件进行检查。 2. you should also initialize sum to 0 or add a check.
2.您还应该将sum初始化为0或添加检查。
here my small fixes: 这是我的小问题:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int * p;
/*
* * Return the sum of the n values in x starting at index 0.
* * Note: x is a pointer to an array of ints.
* * If x is null, then return -1.
* * If n is 0 and x is not null, then return 0.
* */
int sum(int * x, int n);
int main(int argc, char * argv[]){
int * x = new int[argc];
for(int i = 1; i < argc; i++){
string t (argv[i]);
x[i - 1] = std::stoi(t); //it says stoi is not a member of std
}
p = NULL;
cout << "*x is " << (*x) << endl;
int y = sum(x, argc);
cout << "y is " << y << endl;
int z = sum(p, argc);
cout << "z is " << z << endl;
return EXIT_SUCCESS;
}
int sum(int * x, int n){
if(x==NULL) return -1;
int sum = 0;
for(int i = 0; i < n; i++){
sum = sum + x[i];
}
return sum;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.