以下是一个简单的函数,它将两个15位数字相加,两个数字都使用2个字符数组存储。但是,在调试之后,我收到了这个错误:运行时检查失败#2:堆栈变量"携带"被腐败了。
#include <stdio.h>
int main(void){
addition1();
getchar();
getchar();
return 0;
}
int addition1(){
char numberArray1[16] = {4,5,9,2,7,4,9,5,7,1,6,2,0,3,0};
char numberArray2[16] = {0,0,2,7,9,9,8,7,2,5,6,1,0,3,0};
char str[5];
char finalAnswer[16];
int c, c1, c2, c3, answer = 0, a;
int carry[25];
//Displaying number 1
for (c = 0; c < 15; c++){
printf("%d" , numberArray1[c]);
}
printf(" + ");
//Displaying number 2
for(c1 = 0; c1 < 16; c1++){
printf("%d" , numberArray2[c1]);
}
//Addition of the 2 numbers
carry[14] = 0;
for(c2 = 14; c2 >= 0; c2--){
answer = carry[c2] + numberArray1[c2] + numberArray2[c2];
if (answer <= 9){
finalAnswer[c2] = answer;
carry[c2-1] = 0;
}
else{
carry[c2-1] = answer / 10;
a = answer % 10;
finalAnswer[c2] = a;
}
}
printf(" = ");
for (c3 = 0; c3 <= 14; c3++){
printf("%d" , finalAnswer[c3]);
}
getchar();
return 0;
}
有人可以说明我做错了什么吗?
答案 0 :(得分:3)
您的索引变量c2
降至零。因此,通过carry[c2 - 1]
访问无效。