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

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]);
        }
    }
}
    
asked by anonymous 20.10.2017 / 00:17

1 answer

0
  

I would like to change and return the vector to main

When you pass a vector to a function you are 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 Ideone example

Here you see that actually changing the values of the vector inside the muda function changes the original vector that is in main . This happens because the function has received the memory address where the vector is, then it can go to memory and change where it is.

This makes the return useless since it already has the array changed in main .

But if you wanted, you could do it ( although 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 like this:

array = muda(array);
  

I would like to have vetor_y1 returned to main , and start on main

As you saw above, the vetor_y1 function has already changed vetor in main , so just main print directly the values you need.

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

    
20.10.2017 / 01:00