0

This is my code that doesn't work:

#define TAM 5

int vec[TAM];
int revvec[TAM] = {0};

void invertir(int vec[], int revvec[], int i)
{
    if ((TAM - 1 - i) == 0) {
        revvec[i] = vec[0];
    }
    else {
        revvec[i] = vec[TAM - 1 - i];
        invertir(vec, revvec, i++);
    }
}

It compiles well but it gets stuck when executed.

0

2 Answers 2

1

There a problem in your code :

    invertir(vec, revvec, i++);

must be

    invertir(vec, revvec, ++i); /* or i+1 */

else you always give the index 0 to your recurcive calls and you finaly explode the stack

After that correction your code is ok :

#include <stdio.h>

#define TAM 5

int vec[TAM]={ 1,2,3,4,5};
int revvec[TAM]={0};

void invertir(int vec[], int revvec[],int i){
  if (((TAM-1)-i)==0) {
    revvec[i]=vec[0];
  }
  else {
    revvec[i]=vec[(TAM-1)-i];
    invertir(vec, revvec,++i); /* or i+1 */
  }
}

int main()
{
  invertir(vec,revvec, 0);
  for (int i = 0; i != TAM; ++i)
    printf("%d ", revvec[i]);
  putchar('\n');
  return 0;
}

Compilation and execution:

pi@raspberrypi:/tmp/d $ gcc -g -pedantic -Wextra x.c
pi@raspberrypi:/tmp/d $ ./a.out
5 4 3 2 1 

You can also simplify to have :

void invertir(int vec[], int revvec[],int i){
  revvec[i]=vec[(TAM-1)-i];

  if ((TAM-1) != i) {
    invertir(vec, revvec, i + 1);
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

@Swordfish yes the increment is local in the OP code, all recuscive calls get the index 0, this is what I say in my answer
I understand what you are saying in your answer. I just added that it is unnecessary to increment i.
@Swordfish ah yes, can be i+1, I did to be closer to the OP code, I added comment, thank you
The logic to break the recursion is overcomplicated. Just do if (i == TAM) return; and drop the else.
@Swordfish yes, funny, I just did ^^
0

To not tie the function to the use of TAM in the declaration of the arrays but keep it general, pass the arrays length as parameter:

#include <stddef.h>  // size_t

void reverse_impl(int const *src, int *dst, size_t length, size_t pos)
{
    if (pos == length)
        return;

    dst[pos] = src[length - pos - 1];
    reverse_impl(src, dst, length, pos + 1);
}

void reverse(int const *src, int *dst, size_t length)
{
    reverse_impl(src, dst, length, 0);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.