在C语言中,数组中的值如何输入到函数中?

时间:2018-12-03 01:20:28

标签: c arrays

我在使用函数数组时遇到了困难。我希望主程序循环中的array1与该函数中的array1共享相同的值,但是困难重重。我知道这对某些人来说可能很容易,但是作为编程的第一年级学生,预计会出现这样的问题。非常感谢您的帮助。

#include <stdio.h>

int FillArray(int array1[9])
{

    int array1[9], array2[9], i, n=0;


    for (i = 0; i < 9; ++i)
    {
        if  (array1[i] > 0)
            array2[i] = array1[i] * 2;
            else
                array2[i] = array1[i] * 10;

        printf("\n%d", array2[10]);
    }
    return 0;
} /* End of FillArray Function */

int main()
{
    int array1[9] = { 40, 13, -5, 22, 10, 80, -2, 50, 9, -7 };
    FillArray(array1[9]);


}

2 个答案:

答案 0 :(得分:2)

在fillarray()中,打印语句无效。 array2 [10]不是有效范围,因为循环将运行到9。因此,使其小于或等于9。就像这样

array2[i]

或者您可以将其写为

array2[9]

您可以在主函数中将array1 []作为参数传递。您需要这样重写

int main(int array1[])

或者您可以在主要功能中执行此操作

Int main()
{ 
     /* Write what you want /*
      array1[] = { _the_values_you_want to_give}
      fillarray(array1)

希望这会有所帮助

答案 1 :(得分:1)

我希望这会有所帮助:

#include <stdio.h>

/* don't need to specify size of array1 here */
/* rather pass the no. of elements of array1 through n*/

int FillArray(int array1[], int n) {
    /* observe, you've 10 elements in array1 */
    /* that's why array2[10] */
    /* size of array2 should be >= n */
    int array2[10], i;

    /* I replaced 9 with 10 as array1 */
    /* has n elements...ranges 0 to n-1 */
    for(i = 0; i < n; ++i) {
        if  (array1[i] > 0)
            array2[i] = array1[i] * 2;
        else
            array2[i] = array1[i] * 10;


        /* I didn't get this below line. */
        /* Should it be outside the loop? or what you've tried to do here. */
        /* If you want to print the content of array2,*/
        /* then see your book how to print an array */
        /* for an array of size n,*/
        /*it's index range is 0 to n-1.....so 10 is not valid */

        // printf("\n%d", array2[10]); // this line
    }


    /* To print array2, in case if you want to know about it */
    for(i=0; i<n; i++) {
        printf("%d\n", array2[i]);
    }

    return 0;
}

int main() {
    /* you don't have to specify size here */
    /* but again, if you would like to specify */
    /* it would be >= 10 as you've at least 10 elements in array1 */
    int array1[] = { 40, 13, -5, 22, 10, 80, -2, 50, 9, -7 };
    /* it's good habit to pass the no. of elements of an array */
    FillArray(array1, 10);
    return 0;
}