ppedro9
ppedro9

Reputation: 21

I can´t get out my array from a function to the main in c

In escribirVect(suma[MAX]), the compiler tells me that suma is undeclared but I declared it in my function sumarV, how can I use my variable 'suma' in main?

#include <stdio.h>
#define MAX 10

void leerVect(int vect[MAX]);
void escribirVect (int v[MAX]);
void sumarV (int vector1[MAX], int vector2[MAX]);

int main ()
{
    int vector1[MAX], vector2[MAX];
    printf("Introduzca los valores del primer vector: \n");
    leerVect(vector1);
    printf("Introduzca los valores del segundo vector: \n");
    leerVect(vector2);
    sumarV(vector1, vector2);
    escribirVect(suma[MAX]);  // here is the problem

    return 0;
}

void leerVect(int v[MAX])
{
    int i;
    for (i=0; i<MAX; i++)
    {
        printf("Introduzca el valor de v[%d]: ", i);
        scanf("%d", &v[i]);
    }
}

void escribirVect (int v[MAX])
{
    int i;
    for (i=0; i<MAX; i++)
    {
        printf("El valor de la suma de el elemento v[%d] es: %d \n", i, v[i]);
    }
}

void sumarV (int vector1[MAX], int vector2[MAX])
{
    int suma[MAX], i;   //here is the problem
    for (i=0; i<MAX; i++)
    {
        suma[i]=vector1[i]+vector2[i];  //here is the problem
    }
}

The problem disappears when I comment 'here is the problem' inside the code.

Upvotes: 0

Views: 82

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

Declare suma in main and pass it to sumaV()

int main ()
{
    int vector1[MAX], vector2[MAX], suma[MAX];

    ...
    sumarV(vector1, vector2, suma);

Then, in the function

void sumarV (int vector1[MAX], int vector2[MAX], int suma[MAX])
{
    int i;
    for (i=0; i<MAX; i++)
    {
        suma[i]=vector1[i]+vector2[i];
    }
}

Finally, don't pass the number of elements

escribirVect(suma[MAX]);  // here is the problem

just pass the array, which decays into a pointer to the first element:

escribirVect(suma);

Upvotes: 3

Related Questions