문제

long int d[500], i;
d[1] = 1;
d[2] = 2;
d[3] = 4;
for(i = 4; i<=500; i++)
    d[i] = d[i-1] + d[i-2] + d[i-3];

int n = 500;
printf("%ld\n", d[500]);

The compiler is gcc. Bus error occurred at compiling. What caused this to happen?

도움이 되었습니까?

해결책

long int d[500] declares an array with 500 items indexed from 0 to 499

d[500] is outside the bounds of your array.

다른 팁

long int d[500];
....
for(i = 4; i<=500; i++)
            ^^^^^^

You wrote passed the bounds of allocated memory resulting in Undefined behavior.
You are supposed to access array elements only from index 0 to 499 because that is what you allocated.

printf("%ld\n", d[500]); - accessing beyond the array.

d[i] = d[i-1] + d[i-2] + d[i-3]; - accessing beyond the array.

long int d[500] gives you the memory for 500 long digit integers and are assigned for d[0] to d[499] but you are calling d[500] whose value is not defined.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top