首页 > 解决方案 > 使用 pi 的数字时返回错误 3221225725

问题描述

我制作了一个程序,可以识别并返回最高连续重复数字。当我运行程序时,我收到上面列出的错误。我没有调用任何递归函数,只是一个分析数字的函数。代码如下所示。由于明显的原因,我不包括分析的数字,只知道它是 1000 万位。

// pi.c
#include <stdio.h>
#define SIZE 10000000

unsigned int findDigits(const char pi[], char *mostRepeatingDigitPtr, unsigned int *repeatLocationPtr);

int main(void)
{
    // 10 million digits of pi
    const char pi[] = "INSERT 10 MILLION CHARACTERS";
    
    unsigned short int repeatStreak;
    
    char mostRepeatingDigit;
    
    unsigned int repeatLocation;
    
    // pass to findDigits()
    repeatStreak = findDigits(pi, &mostRepeatingDigit, &repeatLocation);
    
    printf("The largest amount of repeating digits was: %hu. The repeated digit was: %c. The position on the array was %u.", repeatStreak, mostRepeatingDigit, repeatLocation);
    
    return 0;
}

unsigned int findDigits(const char pi[], char *mostRepeatingDigitPtr, unsigned int *repeatLocationPtr)
{
    char lastDigit = '3';
    
    unsigned short int repeatStreak = 0;
    
    unsigned short int highestRepeat = 0;
    
    unsigned int repeatLocation = 0;
    
    // loop through 10 million digits
    for (unsigned int i = 0; i < SIZE; ++i) {
        if (pi[i] == lastDigit) {           
            ++repeatStreak;
            
            repeatLocation = i - 1;
        }
        else {          
            if (repeatStreak > highestRepeat) {
                highestRepeat = repeatStreak;
                
                *mostRepeatingDigitPtr = lastDigit;
                
                *repeatLocationPtr = i - repeatStreak;
            }
            
            lastDigit = pi[i];
            
            repeatStreak = 0;
        }
    }
    
    // return highest streak
    return highestRepeat + 1;
}

提前致谢。

标签: c

解决方案


程序崩溃的最可能原因是堆栈溢出

在 Microsoft Windows 上,最大堆栈大小默认设置为大约 1 兆字节。这可以在链接器设置中更改。

通过将 1000 万个字符放入堆栈,您将超出此限制。

一个简单的解决方案是更改线路

const char pi[] = "INSERT 10 MILLION CHARACTERS";

const char *pi = "INSERT 10 MILLION CHARACTERS";

这样一千万个字符就不再直接存储在堆栈上。相反,堆栈上只有一个指针,它指向只读内存中的字符串文字。


推荐阅读