Hi, I have the following code that performs the calculation of a combinational number:
int combinacional(int_pair par) {
int i,j;
int tabla[par.a+1][par.b+1] ;
if(par.b == 0 || par.b == par.a) {
return 1;
}
else if (par.b == 1 || par.b == (par.a - 1)) {
return par.a;
}
else {
for (i=0; i<=par.a; i++) {
tabla[i][0] = 1;
}
for (i=1; i<=par.a; i++) {
tabla[i][1] = i;
}
for (i=2; i<=par.b; i++) {
tabla[i][i] = 1;
}
for (i=3; i<=par.a;i++) {
for (j=2; j<par.a; j++) {
if(j<=par.b) {
tabla[i][j] = tabla[i-1][j-1] + tabla[i-1][j];
}
}
}
}
return tabla[par.a][par.b];
}
In it I make use of "int_pair" which would be an equivalent to a tuple in which the first or second value can be selected, I also create a two-dimensional array to be able to store the values of the Pascal triangle and take the result of this at the end . The error comes when displaying the output, for this I use the following:
void test() {
list enteros = leerFichero4("ficheros/entradaE4.txt");
for (int i = 0; i < enteros.size; i++) {
int_pair tupla = *(int_pair*) list_get(&enteros, i);
int result = combinacional(tupla);
printf("Entrada = %s; ", int_pair_tostring(&tupla, mem));
printf("Salida = %i\n", result);
printf("========================================\n");
}
}
int main() {
test();
}
This shows me the following:
Entrada = (10,1); Salida = 10
========================================
Entrada = (9,2); Salida = 36
========================================
Entrada = (8,3); Salida = 7105
========================================
Entrada = (7,4); Salida = -996404052
========================================
Entrada = (6,5); Salida = 6
========================================
The first two outputs and the last one are correct. However, the others must be 56 and 35 and pointers to memory locations appear, I imagine. I guess it's some pointer error but I can't find it.
So I edit the answer to make it clearer, in case someone enters it looking for information. As @PaperBirdMaster answered me in the comments. The error was that the version used did not allow the creation of arrays where the dimensions varied. Therefore, the array
tabla
was the cause of the problem, since it was built depending on the values received by parameter. Therefore, the solution was to build it with size [100][100], thus being of a fixed size.