Thread overview |
---|
April 08, 2018 stirling numbers and multidimensional arrays | ||||
---|---|---|---|---|
| ||||
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] = 0 ; } for(int i = 0; i <= k; i++) { matrix[0][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)) ; } |
April 08, 2018 Re: stirling numbers and multidimensional arrays | ||||
---|---|---|---|---|
| ||||
Posted in reply to popgen | 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. |
April 10, 2018 Re: stirling numbers and multidimensional arrays | ||||
---|---|---|---|---|
| ||||
Posted in reply to ag0aep6g | 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.
|
Copyright © 1999-2021 by the D Language Foundation