0
double sumArray(double u[])
{

double summ=0.0

for(int i=0; i<sizeof(u)/sizeof(u[0]); i++)
{
    summ=summ+u[i];
}
return summ;
}
int main(){
cout<<"how big is your array";
int Uarraysize;
cin>>Uarraysize;
double Uarray[Uarraysize];

for(int i=0;i<Uarraysize;i++){

cin>>Uarray[i];



}
double summ=sumArray(Uarray);
 cout<<summ;

return 0;

} I am trying to get the size of the parameters of the array u for my for loop in my double sumarray function but it is being read as a double* which equals 8 instead of being read as size*8. Hoping to find out why and how to fix it

nick o
  • 11
  • This won't work since `sizeof(u)` is the size of **a pointer**. You'll need to do: `double sumArray(double u[], std::size_t u_len)` – Eljay Mar 17 '23 at 14:51
  • This is a classic. In `double sumArray(double u[])` `u[]` is a pointer not an array, and `sizeof` is giving you the size of the pointer (which is 8) not the array. You cannot have an array as a function parameter in C++. See the duplicate for details, or consult your favourite C++ book. – john Mar 17 '23 at 14:53
  • See https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay – Solomon Ucko Mar 17 '23 at 14:56
  • 1
    Another classic problem, `double Uarray[Uarraysize];` is not legal C++, because in C++ array bounds must be **constants** and `Uarraysize` is a variable. Obviously your compiler accepts this code but that's a flaw in your compiler, other C++ compilers would reject it. Seems wherever you are learning C++ from is not giving you the facts about C++. – john Mar 17 '23 at 14:56
  • 1
    When used as a function parameter, `double u[]` means `double* u`. – Drew Dormann Mar 17 '23 at 14:58
  • 1
    You probably want to switch and use `std::vector` which should be the first choice in nearly all cases where you need an array that is sized at run time. – drescherjm Mar 17 '23 at 15:28
  • 2
    use `std::size` for arrays. Its a compiler error to call `std::size` with a pointer, rather than nonsense results. `sizeof` should never be used to get the size of an array – 463035818_is_not_an_ai Mar 17 '23 at 16:03
  • Strange. How can one have 0.25 of a location in memory, or the classic 3.14159 of an array? This is why `sizeof()` returns an integral value. – Thomas Matthews Mar 17 '23 at 16:40

0 Answers0