Array as an argument of a function in C++ [duplicate] - c++

This question already has answers here:
How does sizeof know the size of array? [duplicate]
(7 answers)
Using sizeof on arrays passed as parameters [duplicate]
(3 answers)
Closed 2 years ago.
This is a question on C++. I tried defining a function that computes the average of all elements in an array of doubles as follows, through the sizeof function that enables us to compute the length of the array.
#include<iostream>
#include<cstddef>
using namespace std;
double getAverage(double arr[]) {
double sum =0;
double avg;
size_t size = sizeof(arr)/sizeof(*arr); \\ to calculate the length of the array arr
for (size_t i = 0; i < size; ++i) {
sum += arr[i];
}
avg = sum / size;
return avg;
}
int main () {
double balance[] = {1000, 2, 3, 17, 50};
double avg = getAverage(balance) ;
cout << "Average value is: " << avg << endl;
return 0;
}
However, instead of 214.4, it returns 1000, which is clearly wrong. Is it legitimate to pass an array as an argument of a function in C++?

Related

Variable length in a Simple Matrix c++ [duplicate]

This question already has answers here:
Why can't I create an array of size n? [duplicate]
(5 answers)
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 9 months ago.
I'm using VS 2019. In this code:
using namespace std;
int main()
{
cout << "Inserisci la dimensione della matrice:";
int DIM;
DIM = 2;
cin >> DIM;
int v[DIM][DIM];
return 0;
}
I Don't understand why in:
int v[DIM][DIM];
I've this error:
The expression must have a constant value. It is not possible to use the "DIM" variable value as a constant.
In C++, the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
So we cannot use the input given by the user as the size of the array. That is why you are getting the mentioned error.
You can use std::vector in place of built in array to solve your problem.
some compiler/c++ version doesn't support variable length arrays compile time. we can create dynamic array on heap. Below code works for you
using namespace std;
int main()
{
cout << "Inserisci la dimensione della matrice:";
int DIM;
DIM = 2;
cin >> DIM;
int **v = new int*[DIM];
for (int i=0;i<DIM;i++)
v[i] = new int[DIM];
// now you can use it as 2D array i.e
v[0][0] = 12;
cout<<v[0][0];
return 0;
}

C++ code. Can anyone help me understand why this is not working? [duplicate]

This question already has answers here:
What is array to pointer decay?
(11 answers)
Closed 2 years ago.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int SIZES = 4;
int oldvalues[SIZES] = { 10, 100, 2000, 300 };
int newvalues[SIZES];
for (int count = 0; count < SIZES; count++)
newvalues[count] = oldvalues[count];
cout << newvalues << endl;
}
Is there a reason my code is only printing "0x7ffeefbff270" I don't think there is anything missing. My guess is that I have the cout wrong?
When printing out values of an array, you have to specify each element you want to print. You can't print the whole thing at once.
You should put brackets for your for loop (always use brackets!) and include your cout line within those brackets. Then update the cout line to reference the element you just saved - newvalues[count].
Just trying to print the array is giving you a memory address.
#include <iostream>
int main()
{
const int SIZES = 4;
int oldvalues[SIZES] = { 10, 100, 2000, 300 };
int newvalues[SIZES];
for (int count = 0; count < SIZES; count++)
newvalues[count] = oldvalues[count];
for (int count = 0; count < SIZES; count++)
std::cout << newvalues[count] << " "; # Here you need to indicate each element
}

please can someone tell me while the code, when run, prints 1 instead of 3.5 as solution [duplicate]

This question already has answers here:
Length of array in function argument
(9 answers)
Closed 7 years ago.
please can someone tell me why these code, when run prints 1 instead of 3.5 to the console. it implemnts passing an array to a function, to calculate average of the array elements. i used the sizeof(array)/sizeof(int) as array length
#include "stdafx.h"
#include <iostream>
// function avg, to calculate average of an integer array.
double avg(int iArray[])
{
// initialize variable y to calculate sum
// initialize variable to calculate length of array
int y{}, z = sizeof(iArray) / sizeof(int);
// loop over array elements
for (int i{}; i < z; i++)
{
y += iArray[i];
}
// return average to caller
return ((double)y) / z;
}
int main()
{
using namespace std;
// initialize array.
int iArray[] = { 1, 2, 3, 4, 5, 6 };
// call avg function, and assign return value to variable z.
double z = avg(iArray);
// print average to console
cout << z << endl;
return 0;
}
double avg(int iArray[])
{
int y{}, z = sizeof(iArray) / sizeof(int);
is equivalent to
double avg(int* iArray)
{
int y{}, z = sizeof(int*) / sizeof(int);
You need to pass the size of the array from main.
double avg(int iArray[], int z)
{
// initialize variable y to calculate sum
int y{};
// loop over array elements
for (int i{}; i < z; i++)
{
y += iArray[i];
}
// return average to caller
return ((double)y) / z;
}
and in main:
double z = avg(iArray, sizeof(iArray)/sizeof(iArray[0]);

C++: passing and returning pointers to arrays - code not working [duplicate]

This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 7 years ago.
I'm trying to write a function that casts an array of ints into doubles. It takes in a constant pointer to the original int[] array (to avoid unwanted modifications?) and returns a pointer to an array of casted double[]. However, the code that I wrote doesn't seem to be working. Can anyone point out what's wrong with it?
#include <iostream>
using namespace std;
double* castToDouble(const int *input);
int main(){
int integers[] = {1,2,3,4};
double *doubles = castToDouble(integers);
cout << "numElements in doubles: " << sizeof(doubles)/sizeof(double) << endl;
for(int i = 0; i < sizeof(doubles)/sizeof(double); i++){
cout << doubles[i] << endl;
}
return 0;
}
double* castToDouble(const int *input){
// Obtain the number of elements in input.
int numElements = sizeof(input)/sizeof(int);
double *doubleAry = new double[numElements];
cout << "numElements in input: " << numElements << endl;
for(int i = 0; i < numElements; i++){
doubleAry[i] = static_cast<double>(input[i]);
}
return doubleAry;
}
The output of the program is the following:
numElements in input: 2
numElements in doubles: 1
1
The numElements' calculated seem to be arbitrary too. I'm pretty new to c++ and am unable to pinpoint the problem. Thanks in advance.
As you marked it C++, I thought this might be more idiomatic:
#include <vector>
#include <algorithm>
std::vector<double> CastToDouble(std::vector<int> const & ints)
{
auto doubles = std::vector<double>(ints.size());
std::transform(ints.begin(), ints.end(), doubles.begin(), [](int value) -> double {
return static_cast<double>(value);
});
return doubles;
}
int main(int argc, char* argv[])
{
auto values = std::vector<int>() = {
1, 2, 3, 4
};
auto doubles = CastToDouble(values);
}

Why doesn't my add function add all the numbers? [duplicate]

This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 8 years ago.
I am using sizeof trick to get the length of array, but it only looks like it's adding 1 and 2.
#include <iostream>
#include <stdio.h>
using namespace std;
int add(int array[])
{
int sum = 0;
for (int i = 0; i < sizeof(array)/sizeof(array[0]); i += 1)
{
sum += array[i];
}
return sum;
}
int main()
{
int array[4] = {1, 2, 3, 4};
cout << add(array);
return 0;
}
Output is 3. What is wrong?
In a parameter to a function, int array[] is another way of saying int *array, so sizeof(array) will return the size of a pointer-to-int. I’m pretty sure there’s a more idiomatic C++ way of doing this, particularly in the newer versions of C++, but the C way of dealing with this would be to pass a second parameter with the size of the array.