gpt4 book ai didi

c++ - 不知道段错误发生在哪里

转载 作者:行者123 更新时间:2023-11-27 23:17:13 26 4
gpt4 key购买 nike

<分区>

出于某种原因,当我运行这段代码时,当 for 循环中 i 的值为 7654319 时,我得到了一个段错误。然而奇怪的是,当我没有检查该值是否为泛数字时,它正常工作,没有段错误。当我检查它是否只是 pandigital 时它也有效;但不是两者都适用。我使用 gdb 逐步执行代码,这是我得到的输出:

Program received signal SIGSEGV, Segmentation fault.
0x00000000004007d3 in main () at Pand.cc:81
81 if (isPandigital(i) && Primes[i])
6: Primes[i] = <error: Cannot access memory at address 0x7ffefffffff4>
5: i = <error: Cannot access memory at address 0x7ffefffffff4>
4: Primes[7654317] = <error: Cannot access memory at address 0x7ffefffffff8>
3: Primes[7654321] = <error: Cannot access memory at address 0x7ffefffffff8>
2: Primes[7654319] = <error: Cannot access memory at address 0x7ffefffffff8>
1: Primes = <error: Cannot access memory at address 0x7ffefffffff8>

从输出来看,似乎通过在 isPandigital(int) 函数中操纵 i 的值,这也影响了 main 中 i 的值。这对我来说没有任何意义,但我继续在 isPandigital(int) 函数中使用不同的变量来表示 i,但我仍然遇到相同的错误。

有人可以帮帮我吗?这些类型的错误非常烦人,因为一切似乎都应该正常工作,但事实并非如此,解决方案只是将自己隐藏在实现层之下。感谢您的帮助!

#include <cstdio>
#define MAX 7700000

typedef unsigned int uint;

bool* GetPrimes()
{
const int Need = MAX;
bool* Sieve = new bool[Need];

for (int s = 0; s < Need; ++s)
Sieve[s] = 1;

bool Done = false;
uint w = 3;

while (!Done)
{
for (uint q = 3, Prod = w * q; Prod < (uint)Need ; q += 2, Prod = w * q)
Sieve[Prod] = false;

Done = (w > (Need >> 1) ? true : false);

w+=2;
}
return Sieve;
}

bool isPandigital(int num)
{
int arr [] = {1,2,3,4,5,6,7}, G, count = 7;
do
{
G = num%10;
if (arr[G-1])
--count;
arr[G-1] = 0;
} while (num/=10);

return (!count);
}

int main()
{
bool* Prime = GetPrimes();
int i;

for (i = 7654321 ;i > 2; i-=2)
{
if (Prime[i] && isPandigital(i))
break;
}

printf("%d\n", i);

return 0;
}

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