Function and Array in C++: Unexpected output -
i need here please.
i started learning c++ (coming python background).
i'm trying familiarize myself arrays , functions. wrote bunch of functions stated, above each one.
however, function supposed sum elements in array , return sum, seem adding 10 result, no matter argument supplied input. doing wrong please, can't seem find out. on general layout of code appreciated.
// working arrays , functions #include<iostream> using namespace std; // function instantiate array int of length n. int* array_creator(int n) { static int ary_of_ten[10]; //declare array (int i=0; i<n; i++) //use loop fill { ary_of_ten[i] = i+1; } return ary_of_ten; } //function print array elements void* array_printer(int arr[], int array_lenght) { (int i=0; i<array_lenght-1; i++) { cout << arr[i] << " "; } cout << arr[array_lenght-1] << endl; } //function accepts int arrays , 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]; (int i=0; i<ary_sz; i++) { *(sqd_values + i) = *(p+i) * *(p+i); } return sqd_values; } //function accepts int arrays , returns sum of 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 initialized 0.
int summation=0;
Comments
Post a Comment