samedi 11 janvier 2020

Why does sizeof(ar)/ sizeof(ar[0]) not work properly on a vector when passed to a function?

I'm trying to get to know c++ better and came across this confusion.

int simpleArraySum(const vector<int> ar) {
  int n=sizeof(ar)/sizeof(ar[0]);
  int sum=0;
    for (int i=0; i<n; i++){
      sum+=ar[i];
    }
    return sum;
}

When I passed a vector of 10 elements the result was lower than expected. I checked that n=6 unlike when I use size() which gives n=10. My confusion comes since the way the code is written works normally in main with sizeof(ar)/sizeof(ar[0]).

Aucun commentaire:

Enregistrer un commentaire