-2

I am new to coding and I have a double arr[]={1,2,-1.75,6};

I have tried to do

#include <iostream>
#include <math.h>
using namespace std;

void solve (double arr[]){
    int size=(sizeof(arr))/(sizeof(arr[0]));
    cout <<"size: "<<size <<endl;
    return;
}

int main(){
    double arr[]={1,2,0.75,4};
    solve(arr);
    return 0;
}

but I cannot find the size of array with type double. Any help is appreciated thanks!

Kaito Ace
  • 1
  • 2
  • 2
    your `arr` is a function argument? – justANewb stands with Ukraine Jun 04 '22 at 09:09
  • yes it is, solve (double arr[]){} – Kaito Ace Jun 04 '22 at 09:11
  • 1
    In C++, when an array is pass to a function, it decays to a pointer pointing to the first element in the array, so you can't use that. I suggest using `std::vector`. Something like `solve (std::vector arr){}` and when you need the array's size, `use arr.size()` – justANewb stands with Ukraine Jun 04 '22 at 09:13
  • 1
    @justANewbstandswithUkraine if he wants array semantics why not give it to him ;) https://en.cppreference.com/w/cpp/container/array – kallaballa Jun 04 '22 at 09:22
  • Just avoid all this legacy trouble with plain "C" style arrays, use std::array or std::vector for arrays. They've been around since C++11 and obey all the predictable rules for passing by (const) reference. (https://en.cppreference.com/w/cpp/container/array) – Pepijn Kramer Jun 04 '22 at 09:23
  • Yes, i understand that might not be possible with double arr. But for my purposes i require the size of a double arr[]. It is fine if i can push individual elements into a vector and use .size(), but the problem is how to iterate over the double arr[] without an initial size. – Kaito Ace Jun 04 '22 at 09:24
  • @kallaballa Because he's trying to find a size of the array. Array's sizes has to be known at compile time, so I linked him to `std::vector` :) – justANewb stands with Ukraine Jun 04 '22 at 09:25
  • 1
    @KaitoAce You can't. The size of `double arr[]` has to be known at compile time – justANewb stands with Ukraine Jun 04 '22 at 09:27
  • ok let me show what i have, i just want to print size of the arr `//code below` ` #include #include using namespace std; void solve (double arr[]){ int size=(sizeof(predicted))/(sizeof(predicted[0])); cout < – Kaito Ace Jun 04 '22 at 09:32
  • @KaitoAce your question has already been answered. Check the linked duplicates please. – πάντα ῥεῖ Jun 04 '22 at 09:51
  • @KaitoAce also [edit] your question, if you want to add additional information, instead of burying that in comments. – πάντα ῥεῖ Jun 04 '22 at 09:58
  • oh ok @justANewbstandswithUkraine, i understand now, just need to do size before passing it as reference cuz otherwise it degrades to a simple pointer. Wooo, thanks for your help! – Kaito Ace Jun 04 '22 at 10:30
  • Online example of how to use arrays in C++ (not the "C" style arrays) : https://onlinegdb.com/619Y8FzlX – Pepijn Kramer Jun 04 '22 at 12:10

0 Answers0