将数组传递给2个函数

时间:2014-12-09 19:43:25

标签: c++ arrays function

所以我应该编写一个创建和数组的程序,并在main中调用函数3,在函数2中从用户获取10个整数,在函数3中,它以相反的顺序显示函数2中的值。我不确定其余部分是否正确,但我不知道如何让功能3工作(我现在拥有的是绝对错误的,只是一个猜测):

#include<iostream>
using namespace std;

void function2 (int [], int);
void function3 (int [], int);

int main ()
{
    const int size1 = 10;
    int arr[size1];
    function3(arr, size1);
    system("pause");
    return 0;
}

void function2 (int array2[], int size2)
{
    for (int i=0; i<10; i++)
    cin >> array2[i];
}

void function3 (int array3[], int size3)
{
    size3= 10;
    function2(arr, size3);
    for (int i=0; i<10; i++)
    array2[i]=array3[10-i];
}

2 个答案:

答案 0 :(得分:0)

考虑到根据您的作业,您必须以相反的顺序输出数组。这并不意味着您必须反转数组本身。 此外,您应该知道标题std::reverse_copy中声明的标准算法<algorithm>可用于您的作业。

程序看起来像

#include <iostream>

void function2( int [], size_t );
void function3( int [], size_t );

int main()
{
    const size_t size = 10;
    int arr[size];

    function3( arr, size );

    return 0;
}

void function2( int a[], size_t n )
{
    for ( size_t i = 0; i < n; i++ ) std::cin >> a[i];
}

void function3( int a[], size_t n )
{
    function2( a, n );

    for ( size_t i = n; i != 0; i-- ) std::cout << a[i-1] << ' ';
    std::cout << std::endl;
}

如果要输入

0 1 2 3 4 5 6 7 8 9

然后输出

9 8 7 6 5 4 3 2 1 0

答案 1 :(得分:-1)

三项小改动将使这项工作:

function2(arr, size3);

应该是

function2(array3, size3);

array2[i]=array3[10-i];

应该是

cout << array3[9-i];

加上要在输出之间添加的任何空格或换行符。

编辑:crashmstr指出我对堆分配错了。你不会在这里这样做。