Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
swap adjacent element in array using recursion

I wrote a program to swap adjacent element of array using recursion:

static arr_len;

void swap(int *a, int len)
{
        int tmp;

        if(len == 0 )
                return;
        else {
                swap(a, len-1);

                if(len == arr_len-1)
                        return;
                else if (len > 1)
                        len++;

                tmp = a[len];
                a[len] = a[len-1];
                a[len-1] = tmp;
        }
}

int main()
{
        int a[] = {1,2,3,4}, i;
        arr_len = sizeof(a)/sizeof(a[0]);

        swap(a, sizeof(a)/sizeof(a[0]));


        for (i = 0; i< 4; i++)
                printf("%d\n", a[i]);
}

This seems to work as I see output:

2

1

4

3

But soon I put more element in array as:

int a[] = {1,2,3,4,5,6}

I see this output:

2
1
4
5
6
3
*** stack smashing detected ***: ./a.out terminated
Aborted (core dumped)
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

For starters using the global variable arr_len is a bad idea.

In any case your function is invalid. Consider a simplified example when the array contains only 1 or 2 elements. When the array contains one element then you are accessing memory beyond the array using an invalid index equal to len in this statement

tmp = a[len];

The function can look much simpler. For example

void swap( int *a, size_t n )
{
    if ( !( n < 2 ) )
    {
        int tmp = a[0];
        a[0] = a[1];
        a[1] = tmp;
        swap( a + 2, n - 2 );
    }
}    
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda