How to invert a vector in C?

Asked

Viewed 64 times

-1

I created a function to reverse vectors however when I run the program I do not see anything. This is my code for now:

#include<stdio.h>
#define DIMV 30


int lerIntPositivo(){
    int numero;
    do{
        printf("Numeros=");
        scanf("%d", &numero);
    }while(numero<0);
    return numero;
}

void preencherVetor(int vetor[], int nElementos){
    int i;
    for(i=0;i<nElementos;i++)
    vetor[i]=lerIntPositivo();
}
void listarVetor(int vetor[],int nElementos){
int i;
for (i=0;i<nElementos;i++)
    printf("%d\n",vetor[i]);

}
void inverter(int vetor[],int nElementos){
    int i;
    int vi[];
    for(i=0;i<nElementos;i++){
        vi[i]=vetor[nElementos-(1+i)];
        i++;

    }
return vi;
}
int main(){

int rotacoes[DIMV];
preencherVetor(rotacoes,5);
listarVetor(rotacoes,5);
printf(inverter(rotacoes,5));
return 0;
}
  • 2

    printf(inverter(rotacoes,5)); will not print anything, function void inverter is void, so returns nothing to print

1 answer

1


As mentioned by @Ricardopunctual in the comment, its function is void, then it really should not return any value. To return an array in C, it is necessary return a pointer to an allocated memory region large enough to hold the amount of items you want:

int* inverter(int vetor[], int nElementos);

With an implementation similar to this:

int* inverter(int vetor[], int nElementos) {
    int i;
    int* vi = malloc(sizeof(int) * 5);
    
    for(i = 0; i < nElementos; i++) {
        vi[i] = vetor[nElementos - (1+i)];
    }
    
    return vi;
}

Upon receiving the vector value, you can iterate for the items by incrementing the previously allocated memory value and releasing it at the end:

int rotacoes[DIMV];
preencherVetor(rotacoes,5);
listarVetor(rotacoes,5);

int* vetor = inverter(rotacoes,5);

for (int i = 0; i < 5; i++) {
    printf("%i\n", *(vetor+i));
}

free(vetor);

return 0;

The result would be:

Numeros=1
Numeros=2
Numeros=3
Numeros=4
Numeros=5
5
4
3
2
1

Browser other questions tagged

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