Passing a vector to a function in C

Asked

Viewed 92 times

-1

In my C practices, I decided to practice using a vector through a function, using the method of passing by parameter. The goal of the program is to receive the 5 elements of a vector, then show the vector through a function (show). However, after reading the 5 values, just nothing else happens, appearing error message Process returned -1073741819 (0xC0000005). What is the best way to correct the code? Thanks in advance!

#include <stdio.h>
void show(int v[5]);
void main()
{
    int vet[5],i;
    printf("Digite 5 numeros:");
    for(i=0;i<5;i++)
        scanf("%d",&vet[5]);
    show(vet[5]);
}
void show(int v[5])
{
    int i;
    for(i=0;i<5;i++)
        printf("%d",v[5]);
}


  • Here: show(vet[5]); you are passing sixth element of the vector, the one with index 5 (although your vector only has space for 5 elements, with indexes from 0 to 4), and not the vector. Use: show(vet);.

2 answers

0


Hello, so... you’re making some basic C mistakes. First, you must pass the vector without indexing it. So:

show(vet);

Also, in your loops, there yes you should index the vector. So:

printf("%d",v[i]);
scanf("%d"&vet[i]);

I hope I’ve helped.

0

Correcting incorrect use of indexes and making your show function more general:

#include <stdio.h>
void show(int[], int);
int main()
{
    int vet[5],i;
    printf("Digite 5 numeros:");
    for(i=0;i<5;i++)
        scanf("%d", &vet[i]);
    show(vet, 5);
    return 0;
}
void show(int v[], int n)
{
    int i;
    for(i=0;i<n;i++)
        printf("%d", v[i]);
}
  • "show(vet[], 5);" this does not compile...

  • As already said in the comment: use show(vet, 5);. Missed delete unnecessary. corrected.

Browser other questions tagged

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