简体   繁体   English

我无法将数组从函数中取出到 c 中的 main

[英]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 ?escribirVect(suma[MAX]) ,编译器告诉我suma未声明,但我在函数sumarV声明了它,如何在main使用我的变量“suma”?

#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.当我在代码中评论“这是问题”时,问题就消失了。

Declare suma in main and pass it to sumaV()main声明suma并将其传递给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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM