Search code examples
c++arrayspointersnew-operatordelete-operator

Why does this new [ ] and delete [ ] implementation break down for integers > 12?


The problem: I need to print the Pascal triangle for any (unsigned int) input passed as a command line argument. All the values must be stored in a LINEAR array and elements must only be manipulated as dereferenced pointers. Following this, the array elements must printed as a lower triangular matrix and subsequently deleted. My implementation functions perfectly for input ranging from 0 to 12 but produces spurious results for higher values.

I tried two different implementations.

  1. Declare a pointer to an array of size (n+1)*(n+2)/2 (which is the number of elements in the triangle for input 'n'). Assign/print variables within a nested loop. Delete the pointer once both loops have been executed.

  2. Run a nested loop, 0 <= i <= n, and 0 <= j <= i. Declare a pointer to an array of size (i+1) in the outer loop. Assign/print elements in the inner loop. Delete the pointer once the inner loop has been executed.

// VERSION 1
unsigned N = (n+1)*(n+2)/2;
  unsigned* elements = new unsigned[N];
  for(i = 0; i <= n; i++) {
    for(j = 0; j <= i; j++) {
      *(elements + j+(i*i+i)/2) = fact(i) / (fact(j) * fact(i-j));
          // print statement
    }
        cout << endl;
  }
delete [] elements;

// VERSION 2
for(i = 0; i <= n; i++) {
    unsigned* elements = new unsigned[i+1];
    for(j = 0; j <= i; j++) {
      *(elements + j) = fact(i) / (fact(j) * fact(i-j));
          // print statement
    }
    delete [] elements;
    cout << endl;
  }

Both these versions were tried separately on Xcode. In both cases, the triangle printed correctly until the 12th layer, i.e. n=12, but generated incorrect results for higher values.

0 | 1 
1 | 1 1 
2 | 1 2 1 
3 | 1 3 3 1 
4 | 1 4 6 4 1 
5 | 1 5 10 10 5 1 
6 | 1 6 15 20 15 6 1 
7 | 1 7 21 35 35 21 7 1 
8 | 1 8 28 56 70 56 28 8 1 
9 | 1 9 36 84 126 126 84 36 9 1 
10 | 1 10 45 120 210 252 210 120 45 10 1 
11 | 1 11 55 165 330 462 462 330 165 55 11 1 
12 | 1 12 66 220 495 792 924 792 495 220 66 12 1 
13 | 1 4 24 88 221 399 532 532 399 221 88 24 4 1 
14 | 1 0 1 5 14 29 44 50 44 29 14 5 1 0 1 
15 | 1 1 0 0 2 4 7 9 9 7 4 2 0 0 1 1 
16 | 1 0 0 0 0 4 0 1 1 1 0 4 0 0 0 0 1 

The debugger, to the extent that I can use it, produced no error messages.

What is happening and how do I fix it?


Solution

  • fact(i) overflows really fast. I haven't checked the numbers, but I'm pretty sure that's what's happening.

    Instead, use the fact that a number in Pascal's triangle is the sum of the two numbers above it.

    Wikipedia has a nice animation for this.