-1

I am a C++ beginner and recently discovered making my own functions and libraries. So i thought that i would make a library as a project. I implemented a function in it, which returns the number of elements in an array. But as I found on most websites, and with my own understanding, using "sizeof(array) / sizeof(array[0]);" works... but not for me. I have an array of 5 elements and the compiler is giving the output "1". Here are the codes of both files:

Main.cxx:

    #include <iostream>
    #include "SML"

    using namespace std;

    int main() {

          int arr[] = {10, 20, 30, 40, 50};

          cout << Int.countof(arr) << endl;
   
          return 0;   

    }

SML(Header):

    // SMLlib:
    // Simple Math Library for C++
    // Created by Saadat Khurshid

    // integer functions
    class Int {

    public:

        // int array count
        int countof(int arr[]) {    
            int count = sizeof(arr) / sizeof(arr[0]);
            return count;
        }
    }; 
    
    // Making object of Int class
    Int Int;

Note: I am using clang-based Cxxdroid android compiler. All the features working on PC IDE's works on it(except ofcourse some windows only libraries).

  • Isn't or isn't not, that's an exremly vague and poor description of an observed symptom anyways. – πάντα ῥεῖ Mar 13 '21 at 19:03
  • Does this answer your question? [C sizeof a passed array](https://stackoverflow.com/questions/5493281/c-sizeof-a-passed-array) – Yksisarvinen Mar 13 '21 at 19:14
  • 1
    @Yksisarvinen in normal circumstances that is a fine duplicate, but the op function is to find the size of the array, all the answers point to the trivial solution which is to pass the size as argument, that wouldn't be a very useful function. – anastaciu Mar 13 '21 at 19:17

1 Answers1

1

"sizeof(array) / sizeof(array[0]);" works... but not for me.

That's because when you pass the array as an argument of the function, it decays to a pointer to the first element of the array, sizeof(arr) will give you the size of the pointer, not the size of the array.

It works when it's used in the same scope where the array is declared. Try it in your main function, where you declare the array, you'll see that it works.

In any case, you should simply use one of the containers provided in the C++ containers library, it would save you time and patience. Seems that an std::array or std::vector is what you need, any of these already has a member that keeps its own size.

anastaciu
  • 23,467
  • 7
  • 28
  • 53