Pascal's triangle - program crashes at the end

Hi,

i have built the following c++ program to create a Pascal's triangle. It works fine for a 5-row triangle but crashes when i try to make a 10-row triangle. It does show the 10-row triangle before crashing though.

Why is it happening?

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

using namespace std;

int main()
{
    int level=10;
    level--;
    int i, k;
    int ptriangle [level][level];

    for (i=0; i<=level; i++)
    {
        ptriangle[i][0]=1;
        ptriangle[i][i]=1;
        for(k=1; k<i; k++)
        {
            ptriangle[i][k]=   ptriangle[i-1][k-1]  +   ptriangle[i-1][k];
        }
    }

     for (i=0; i<=level; i++)
    {


      cout<<"\n";
      for(k=0; k<=i; k++)
        {
            cout<<ptriangle[i][k]<<" ";
        }

    }



Last edited on
It's overflowing the array.

at line 12
for (i=0; i<=level; i++)
the <= means i takes each value from 0 to level

But the array int ptriangle [level][level]; allows valid subscripts only in the range
0 to level-1
thus one extra row and one extra column outside the array are being used, thus corrupting some memory not owned by the program.


Also, the code uses a variable-length array which is not standard c++. level should be declared as const

Thank you. It works!

I also noticed that after level 37 I'm getting negative numbers. Do you know why it's happening?

Thanks again.
Negative numbers - in this case it is because the value being stored exceeds the capacity of the integer type.

An int is usually a 32-bit binary value, with the highest-order bit used to represent the sign. You can squeeze a little bit more capacity by using unsigned integers
 
unsigned int ptriangle [level+1][level+1];


However I'd recommend here using type long long which will usually be a 64-bit integer
 
long long ptriangle [level+1][level+1];


There's some information about different types in the tutorial
http://www.cplusplus.com/doc/tutorial/variables/

See also the example at the bottom of this page on numeric limits:
http://www.cplusplus.com/reference/limits/numeric_limits/
Topic archived. No new replies allowed.