I learned to pass a vector as parameter, I would like to change and return the vector (vector_y1) to main, is there any way to do it without allocating? Please

Asked

Viewed 177 times

0

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int vetor_y1();
int main(){
    setlocale(LC_ALL, "Portuguese");
    int i,j;
    printf("Inf. o tamanho do vetor: ");
    scanf("%d",&i);


    int vetor[i];
    for(j=0;j<i;j++){
        printf("Inf. o %dº valor: ",j+1);
        scanf("%d",&vetor[j]);
    }

    vetor_y1(vetor, j);


    printf("\n");
    system("pause");
    return 0;
}
int vetor_y1(int vetor[], int j){
    int i=j;
    int vetor_y1[j];
    for(j=0;j<i;j++){
        vetor_y1[j]=vetor[j];
    }
    printf("Vetor Y\n");
    for(j=0;j<i;j++){
        if(vetor_y1[j]>=10 && vetor_y1[j]<=40){
            printf("%d ",vetor_y1[j]);
        }
    }
}
  • Without allocating what? Is there any requirement for the code to be like this? It can be much simpler than this.

  • The vector received in the function is a pointer, so when it changes the function already changes the values, and so it makes no sense to return

  • I am learning, so I would like to make the vector y1 return to main, and printar na main, but it is not necessary since I did the exercise, I just have this doubt and I would like to learn but I could not

  • There is no requirement, just want to learn to return it and printar na main

1 answer

0


I would like to change and return the vector to main

When you pass a vector to a function you’re actually passing the pointer to the first element.

Consider the following example:

void muda(int arr[]){
    arr[0] = 9;
}

int main(){
    int array[5] = {1,2,3,4,5};
    muda(array);

    printf("%d", array[0]); //9
}

See the example in Ideone

Here you see that in fact changing the values of the vector within the function muda changes the original vector that is in the main. This is because the function received the memory address where the vector is, so it can go to memory and change where it is.

This makes the return useless since you already have the array changed in the main.

But if I wanted I could do it (although it is not advised):

int* muda(int arr[]){ //aqui o tipo tem de ser definido como ponteiro para int
    arr[0] = 9;
    return arr;
}

And call it that:

array = muda(array);

would like to make the vetor_y1 return to the main, and printar na main

Just as you saw above the function vetor_y1 has already modified the vetor in main, soon enough in the main print directly the values you need.

The return of a vector would only make sense if it had generated a new vector within the function. I also advise to deepen your studies in pointers that will give you a much clearer idea of how all this works.

Browser other questions tagged

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