1

So I'm trying to make a function that gets the length of an array by returning the sizeof the array and sizeof the integer type...

code:

#include <cstdio>
#include <iostream>
using namespace std;

int len(int *thing) {
    return sizeof(thing) / sizeof(int);
}

int main() {
    int fard[] = {100, 45, 1, 723, 500};
    cout << len(fard);
}

... and when I run the code it just returns with 1

how do I fix this / what did I do wrong.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
farderer
  • 61
  • 4

3 Answers3

2

The function parameter has a pointer type

int len(int *thing) {
    return sizeof(thing) / sizeof(int);
}

Even if you will rewrite the function like

int len(int thing[]) {
    return sizeof(thing) / sizeof(int);
}

nevertheless the compiler will adjust the array type of the function parameter to the type pointer to the array element type as written in the first function declaration.

So within the function the expression sizeof(thing) yields the size of a pointer. If the size of a pointer is equal to the value of sizeof( int ) then the function returns 1.

You could write instead

template <size_t N>
size_t len(const int ( &thing )[N] ) {
    return N;
}

and then

cout << len(fard);

to get the number of elements in the array fard.

Pay attention to that there is already standard C++ function std::size declared in the header <iterator> in C++ 17.

So you could write

#include <iterator>

//...

std::cout << std::size(fard);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Because sizeof(thing) / sizeof(int) is probably equivalent to 4 / 4 == 1. Because thing is a pointer and pointers have a size of 4 bytes on 32-bit compilers.

Here:

len(fard)

when you pass fard to the function, it decays to a pointer. This means that it loses its size information. So inside the function len you are dividing a single pointer by sizeof(int).

digito_evo
  • 3,216
  • 2
  • 14
  • 42
0

Try this instead

#include <cstdio>
#include <iostream>
using namespace std;

template< std::size_t N >
int len(int (&thing)[N] ) {
    return sizeof(thing) / sizeof(int);
}

int main() {
    int fard[] = {100, 45, 1, 723, 500};
    cout << len(fard);
}

Result:

Program stdout
5

Code: https://godbolt.org/z/qzdbqEYx1

By the way, on x86_64 your original code returns 2 = sizeof(64 bit pointer)/sizeof(32 bit int)