简体   繁体   English

C ++中的函数和数组:意外输出

[英]Function and Array in C++: Unexpected output

I need some help here please. 我在这里需要一些帮助。

I just started learning C++ (coming from Python background). 我刚刚开始学习C ++(来自Python背景)。

I'm trying to familiarize myself with arrays and functions. 我正在尝试使自己熟悉数组和函数。 Wrote a bunch of functions to do as stated, above each one. 如上所述,编写了一系列功能以供执行。

However, the function which is supposed to sum elements in an array and return their sum, seem to be adding 10 to the result, no matter the argument supplied as input. 但是,该函数应该对数组中的元素求和并返回它们的和,似乎将10加到结果中,而不管作为输入提供的参数如何。 What am I doing wrong please, as I can't seem to find this out. 请问我在做什么错,因为我似乎无法找到答案。 Any help on general layout of my code also would be appreciated. 我的代码的一般布局的任何帮助也将不胜感激。

// WORKING WITH ARRAYS AND FUNCTIONS

#include<iostream>

using namespace std;

// FUNCTION TO INSTANTIATE ARRAY INT OF LENGTH N.
int* array_creator(int n)
{
    static int ary_of_ten[10];  //declare array
    for (int i=0; i<n; i++)   //use loop to fill it up
    {
        ary_of_ten[i] = i+1;
    }
    return ary_of_ten;
}

//FUNCTION TO PRINT ARRAY ELEMENTS
void* array_printer(int arr[], int array_lenght)
{
    for (int i=0; i<array_lenght-1; i++)
    {
        cout << arr[i] << " ";
    }
    cout << arr[array_lenght-1] << endl;
}

//FUNCTION ACCEPTS INT ARRAYS AND RETURNS ARRAY OF SQUARE OF EACH ELEMENT
int* square_array(int *p, int array_length)
{
    const int ary_sz(array_length);
    static int sqd_values[10];
    for (int i=0; i<ary_sz; i++)
    {
        *(sqd_values + i) = *(p+i) * *(p+i);
    }
    return sqd_values;
}

//FUNCTION ACCEPTS INT ARRAYS AND RETURNS SUM OF ITS ELEMENTS
int sum_array(int *arry, int array_length)
{
    int summation;
    for(int i=0; i<array_length; i++)
    {
        summation += *(arry + i);
    }
    return summation;
}

int main()
{
    cout << sum_array(array_creator(10), 3) << endl;
    array_printer(array_creator(10), 10);           //print array of 1-10 elements
    array_printer(square_array(array_creator(10), 10), 10);     //prt arry of sqrd values
    return 0;
}

summation shuld be initialized to 0. 总和应初始化为0。

int summation=0; int sumsum = 0;

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

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