0

I'm very new to C++. From examples, I find this use of sizeof in order to retrieve the length of an array

int main()
{
int newdens[10];
// the first line returns 10 which is correct
std::cout << "\nLength of array = " << (sizeof(v1)/sizeof(*v1)) << std::endl;
std::cout << "\nLength of array = " << (sizeof(v1) << std::endl; //returns 40
std::cout << "\nLength of array = " << (sizeof(*v1)) << std::endl; //returns 4
    }

But if i wrote a function like this

#include <iostream>

void myCounter(int v1[])
    {
    int L, L2, L3;
    L = (sizeof(v1)/sizeof(*v1)); 
    L2 = (sizeof(v1)); 
    L3 = (sizeof(*v1)); 
    std::cout << "\nLength of array = " << L << std::endl;
    std::cout << "\nLength of array = " << L2 << std::endl;
    std::cout << "\nLength of array = " << L3 << std::endl;

    }

int main()
{
int v1[10];

std::cout << "\nLength of array = " << (sizeof(v1)/sizeof(*v1)) << std::endl;
std::cout << "\nLength of array = " << (sizeof(v1)) << std::endl;
std::cout << "\nLength of array = " << (sizeof(*v1)) << std::endl;

myCounter(v1);
    }

the outputs are L=2, L2 = 8, L3 = 4. I can't understand where the problem is.

How to retrieve the correct lenght of v1 inside the function?

marcoresk
  • 1,837
  • 2
  • 17
  • 29

1 Answers1

2

Your problem here is that sizeof() is resolved at compile time. As it has no information about how large is your array, it cannot tell its size. It interprets it as a pointer to an int, which is 64-bit on your machine.

The best way for you is to use std::vector instead of C-style array and use its method size().

Benjamin Barrois
  • 2,566
  • 13
  • 30