## digitalmars.D.learn - stirling numbers and multidimensional arrays

• popgen (46/46) Apr 08 2018 I am trying to implement some code to calculate Stirling numbers.
• ag0aep6g (7/17) Apr 08 2018 [...]
• popgen (3/15) Apr 10 2018 Thank you for your help! And I learned two things, the error in
```I am trying to implement some code to calculate Stirling numbers.
The code shown below provides the correct calculation but throws
a Segmentation fault: 11 once it is done running. I suspect there
is something with the way I am setting up the multidimensional
array.

import std.stdio;
import std.datetime ;
import std.conv ;
import std.file;
import std.string;
import std.regex;
import std.bigint ;
import std.range : enumerate;

int stirling1(int n, int k)
{
auto matrix = new int[][](n+1,k+1) ;
for(int i = 0; i <= n; i++)
{
matrix[i] = 0 ;
}
for(int i = 0; i <= k; i++)
{
matrix[k] = 0 ;
}
for(int i = 1; i <= n ; i++)
{
for(int q = 1; q <= i ; q++)
{
if(q == 1 || i == q)
{
matrix[i][q] = 1 ;
}
else
{
matrix[i][q] = q*matrix[i-1][q] +
matrix[i-1][q-1] ;
}
}
}
return(matrix[n][k]) ;
}

void main()
{
writeln("s(n,k) for s(7,2)") ;
writeln(stirling1(7,2)) ;
}
```
Apr 08 2018
```On 04/08/2018 06:15 PM, popgen wrote:
I am trying to implement some code to calculate Stirling numbers.  The
code shown below provides the correct calculation but throws a
Segmentation fault: 11 once it is done running. I suspect there is
something with the way I am setting up the multidimensional array.

[...]
int stirling1(int n, int k)
{
auto matrix = new int[][](n+1,k+1) ;

[...]
for(int i = 1; i <= n ; i++)
{
for(int q = 1; q <= i ; q++)

Should it be `q <= k` here? You're using q as an index into an array of
length k + 1. If you go up to i, you'll exceed that and go out of bounds.

That you're seeing a segfault instead of a range error indicates that
you're compiling with -release. Better not do that when debugging.
```
Apr 08 2018
```On Sunday, 8 April 2018 at 16:51:14 UTC, ag0aep6g wrote:
On 04/08/2018 06:15 PM, popgen wrote:
[...]

[...]
[...]

[...]
[...]

Should it be `q <= k` here? You're using q as an index into an
array of length k + 1. If you go up to i, you'll exceed that
and go out of bounds.

That you're seeing a segfault instead of a range error
indicates that you're compiling with -release. Better not do
that when debugging.

Thank you for your help! And I learned two things, the error in
the code and not to use -release while debugging.
```
Apr 10 2018