Does anyone know why there’s a glitch in this program?

Asked

Viewed 63 times

0

void ordenar(struct piloto *vetor,int contador_pilotos)
{
    int z,i,x,j; 
    for(x=contador_pilotos-1;x<=1;x--)
    {
        for(i=0;i>x;i++)
        {
            if(strcmp(vetor[i].nome,vetor[i+1].nome)>0)
            {
                strcpy(z,vetor[i].nome);
                strcpy(vetor[i].nome,vetor[i+1].nome);
                strcpy(vetor[i+1].nome,z);
            }
        }
    }
    for(j=0;j<=contador_pilotos;j++)
    {
        printf("%s",vetor[j].nome);
    }
}
  • 1

    What’s the mistake, my son?

  • simply the crash program :/

  • 1

    as far as I know, strcpy uses 2 char vectors as parameter, so this variable z of type int in strcpy(z,vector[i].name); should give problem

  • 1

    Asked 13 minutes ago by user64362. How is that? Who is the author of the question?

  • 6

    @Victorstafusa premature suicide :)

1 answer

0

Its first structure is, does not start or stays in an infinite loop.

for(x=contador_pilotos-1;x<=1;x--)

You can see that contador_piloto can be any value, > 1 or < 0. So:

  • When contador_piloto < 0 x will decrease forever as it will always be less than or equal to 1;
  • When contador_piloto > 2 x will be 2 and when x <= 1, x will decrease, but that will not happen because x is not inside the instruction.

To correct this error, the condition must be changed:

for(x=contador_pilotos-1;x>0;x--)
// ou
for(x=0;x<contador_pilotos;x++)

Another mistake is the copy part, z must be a vector of Char. char z[512], then the exchange is made.

strcpy(z, vetor[i].nome);
strcpy(vetor[i].nome,vetor[i+1].nome);
strcpy(vetor[i+1].nome,z);

Take a look at sorting algorithms: Ordination Comp Sort

Browser other questions tagged

You are not signed in. Login or sign up in order to post.