gpt4 book ai didi

c++ - 段错误 |计算阶乘 |超出索引

转载 作者:行者123 更新时间:2023-12-02 10:52:27 25 4
gpt4 key购买 nike

我在在线 IDE 上解决的许多问题中都遇到了这种段错误,但我无法完全理解这个问题并因此解决它。请帮助我。
我知道它有时会由于堆栈溢出而发生,因此,我应该使用堆内存。但是怎么做呢?
一个例子是这个查找大数阶乘的代码
代码

// calculate factorial of really large numbers

#include<iostream>
using namespace std;
#define MAX 500

int multiply(int arr[], int x, int len)
{
int carry = 0;
int i = 0;
int temp = 0;



for(; i < len; i++)
{
// multiply each digit w the number x and store the carry to be added in the next number
temp = 0;
temp = x * arr[i] + carry;
arr[i] = (temp%10);
carry = temp/10;
}

// if end carry is also generated, even that has to be accomodated in the ans
while(carry != 0) //18 === 8 1
{
temp = carry%10;
carry /= 10;
arr[i] = temp;
len++;
i++;
}
// final length of the number is returned so that it can be printed easily
return len;
}

void factorial(int n)
{
int arr[MAX];


// The array initially contains 1
arr[0] = 1;
int arrLeng = 1;

// multiply the nth number with n+1 to obtain the factorial
for(int i = 2; i <=n; i++)
arrLeng = multiply(arr, i, arrLeng);

// print the final ans array though in reverse order
for(int i = arrLeng-1; i >= 0; i--)
cout<<arr[i];
cout<<endl;
}

int main()
{
// input the number
int n;
cin>>n;

// call the main function
factorial(n);
return 0;
}

最佳答案

arrLeng超过硬编码 MAX 500 的限制。
您应该始终检查索引。它不应超过 MAX 限制。这不是堆栈或堆上的内存分配问题。

关于c++ - 段错误 |计算阶乘 |超出索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64246413/

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