Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
intercambiar elementos adyacentes en una matriz usando recursividad

Escribí un programa para intercambiar elementos adyacentes de una matriz usando recursividad:

 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]); }

Esto parece funcionar como veo salida:

2

1

4

3

Pero pronto puse más elementos en la matriz como:

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

Veo esta salida:

 2 1 4 5 6 3 *** stack smashing detected ***: ./a.out terminated Aborted (core dumped)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Para empezar, usar la variable global arr_len es una mala idea.

En cualquier caso, su función no es válida. Considere un ejemplo simplificado cuando la matriz contiene solo 1 o 2 elementos. Cuando la matriz contiene un elemento, está accediendo a la memoria más allá de la matriz utilizando un índice no válido igual a len en esta declaración

 tmp = a[len];

La función puede parecer mucho más simple. Por ejemplo

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!