0
In an exercise, I need to compare a certain number of distances and tell which are the smallest and print them out. For this, I have the following function:
void Permuta(FILE *saida, Cidade *C, int *sequencia, int inicio, int termino, int totalViagens, float **distanciasAux)
{
int i, j;
totalViagens = TotalViagens(termino);
if(inicio == termino)
{
for(i = 0; i < termino; i++)
fprintf(saida, "%d\t", sequencia[i]+1);
fprintf(saida, "= %f\n", Distancia(C, termino, sequencia));
*distanciasAux = (float *) malloc(totalViagens*sizeof(float));
float *distancias = *distanciasAux;
distancias[i] = Distancia(C, termino, sequencia);
printf("\n%f\n", distancias[i]);
}
else
{
for(j = inicio; j < termino; j++)
{
Troca((sequencia+inicio), (sequencia+j));
Permuta(saida, C, sequencia, inicio+1, termino, totalViagens, distanciasAux);
Troca((sequencia+inicio), (sequencia+j));
}
}
}
In this function, I make the dynamic allocation as follows, as can be seen above
*distanciasAux = (float *) malloc(totalViagens*sizeof(float));
float *distancias = *distanciasAux;
distancias[i] = Distancia(C, termino, sequencia);
printf("\n%f\n", distancias[i]);
In printing these results, I have the correct distance values. However, to compare these values, I need to do it in another function. This other function can be seen below:
void CriaSequencia(FILE *saida, Cidade *C, int *sequencia, int numeroCidade, int totalViagens)
{
int i;
totalViagens = TotalViagens(numeroCidade);
float *distancias;
for(i = 0; i < numeroCidade; i++)
{
sequencia[i] = i;
}
Permuta(saida, C, sequencia, 0, numeroCidade, TotalViagens(numeroCidade), &distancias);
for(i = 0; i < totalViagens; i++)
printf("\n%f\n", distancias[i]);
}
I didn’t start the comparison process because I wanted to make sure that the past values are correct. However, when asking to print the values outside the function, all I get are null values (0.000000).
I would like to know why the impression of the correct values is not taking place and what may be generating this problem.
sequencia+inicio
. Here we have tosequencia
is a pointer andinicio
is a whole. His idea was to use&sequencia[inicio]
?– Victor Stafusa
How is the function
Troca
?– Victor Stafusa