Pass vector by reference or value?

2

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

#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.

    
asked by anonymous 28.12.2016 / 15:35

1 answer

2

You have several errors in your code, especially when declaring variables and functions when you're actually just going to use them, but none that are in the question. You only define the type of the variable or function when it is declaring, when it will access the variable or call the function, it can not put the type, so it is not even calling anything.

An array is already passed by reference every time.

I took the time to organize and modernize it, 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);
}

See running on ideone .

    
28.12.2016 / 15:52