GetMatrixElement is defined as
[...]
and therefore should not change the counters (although n and p exist there too, they are different variables because of locality). In addition, a proposed side-effect would start with the first call, not the 16th.
Actually no: KNNMax is the maximal number of clusters, into which the data can be sorted. Following the conventional nomenclature in multivariate statistics, n is the number of items (say, persons participating in a study), p the number of variables. Thus, problems would occur only if k (actual number of clusters) is larger than KNNmax, but that is prevented by the calling routine. Indeed, KNNmax is a global constant and set to 15, k is set by the calling routine to 2 for the time being.
In other words, the guilty line isj shouldn't be 16, because of this declaration:, because when j = 16, p is correct before and wrong afterwards.
Sums[j] := Sums[j] + x;
Try enabling range checking.