在C++中模拟自上而下添加时出现分段错误
Segmentation Fault while simulating top-down addition in C++
我正试图用C++编写一个程序,该程序接收两个包含数字的字符串,并将它们相加以返回一个"sum"(也是一个字符串)。我已经用Java和Python编写了类似的程序,所以我决定在学习C++的同时,我还不如写一些类似的程序。我不知道为什么我会收到错误,而且在使用Visual Studio或g++编译时也没有收到任何错误。
以下是对主程序中有问题的函数的引用。
Number base(NULL);
Number r = base.addNums("1", "1");
cout << r.toString() << endl;
我已经确保我有一个如下的构造函数来引用addNums函数:
Number(void){}
我写了一些评论,试图解释我在写头文件时的思考过程。有问题的方法如下:
Number addNums(string in1, string in2){
// Calling number 1: X, and number 2: Y
const char* x;
const char* y;
x = in1.c_str();
y = in2.c_str();
// Flag for one number having more digits
bool flag = false;
// Flag for X having more digits
bool xIsBigger = false;
// For storing the sum later
string summ = "";
// Check and see if the flags are needed
if (!(strlen(x) == strlen(y))){
flag = true;
if (strlen(x) > strlen(y)){
xIsBigger = true;
}
}
// Prepend the zeroes to the necessary variable
// to make it work as written addition does
if (flag){
if (xIsBigger){
string zeroes;
for (unsigned int i = 0; i < (strlen(x) - strlen(y)); ++i){
zeroes += "0";
}
string newYStr = zeroes + in2;
const char* newY = newYStr.c_str();
// Add zeroes to Y variable
y = newY;
} else{
string zeroes;
for (unsigned int i = 0; i < (strlen(y) - strlen(x)); ++i){
zeroes += "0";
}
string newXStr = zeroes + in1;
const char* newX = newXStr.c_str();
// Add variables to X value
x = newX;
}
}
// If we encounter x + y > 9, we need this
int carry = 0;
// Current digit being processed
char digitX, digitY;
// Digit to be carried
char toCarry;
// Iterate through the number right to left
// to simulate top-down addition
for (int i = strlen(x) - 1; i >= 0; --i){
digitX = x[i];
digitY = y[i];
// If we're carrying a 1, add it to the top number
if (carry > 0){
digitX += 1;
carry = 0;
}
// Add together the two numbers stored in characters
int currentSum = atoi(&digitX) + atoi(&digitY);
// If x + y > 9, we need to carry
if (currentSum > 9){
string sumString = "" + currentSum;
// Max possible is 9 + 9, so we only have to carry 1
carry = 1;
// Add the second digit in the number to the position in the sum
summ = sumString.at(1) + summ;
}
// Didn't need a carry
else{
string sumString = "" + currentSum;
summ = sumString + summ;
}
}
// Return the object containing the sum
return Number(summ);
}
我对指针的使用相对陌生,但在学习更多的语言和编写这个程序的过程中,通过大量的语法和语言细节的谷歌搜索,我被迫使用它们。
很抱歉,我无法提供更多信息,我感谢任何能帮助我的帮助或批评。
提前感谢!
"ring newYStr'可能超出范围?尝试在顶部声明它,然后进行检查。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?