gpt4 book ai didi

c - 变量 "carry"周围的堆栈已损坏

转载 作者:太空宇宙 更新时间:2023-11-04 07:12:55 25 4
gpt4 key购买 nike

下面是一个简单的函数,它将两个 15 位数字相加,两个数字都使用 2 个字符数组存储。然而,在调试之后,我得到了这个错误:Run-Time Check Failure #2: Stack around the variable "carry"was corrupted。

#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;
}

有人可以指出我做错了什么吗?

最佳答案

您的索引变量 c2 降为零。所以通过carry[c2 - 1]访问是无效的。

关于c - 变量 "carry"周围的堆栈已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26911027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com