Pass vector by reference or value?

Asked

Viewed 4,789 times

3

I want to create two functions, one is to fill a vector with random numbers. The other function is to show the contents of the filled vector. So I did it this way:

#include <stdio.h>
#include <stdlib.h>
int vetor[5];

void inicia(int v[5]){
    int i;
    for(i=0;i<5;i++){
        v[i] = 1 + rand() % 20;
    }
}

void mostra(int v[5]){
    int i;
    for(i=0;i<5;i++){
        printf("%d", v[i]);
    }
}

int main(){
    void inicia(int vetor[5]);
    void mostra(int vetor[5]);

    return 0;
}

I wanted to understand why the "show" function is not printing the value.

1 answer

4


There are several errors in your code, especially of declaring variables and functions when in fact will only use them, but none that is in the question. You only set the type of the variable or function when you are declaring, when you will access the variable or call the function, you cannot type, so you are not calling anything.

A array is already passed by reference always.

I took the opportunity to give an organized and modernized, and improved the scope. Do not create global variables unless you know why you are doing this.

#include <stdio.h>
#include <stdlib.h>

void inicia(int v[5]) {
    for (int i = 0; i < 5; i++) v[i] = 1 + rand() % 20;
}

void mostra(int v[5]) {
    for (int i = 0; i < 5; i++) printf("%d\n", v[i]);
}

int main() {
    int vetor[5];
    inicia(vetor);
    mostra(vetor);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks for the help, bro!

Browser other questions tagged

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