1

I am trying to recursively count down from an array. I have done this previously in python, but I am having trouble finding the size of array. My sizeof() function is only returning a length of 2, which is odd since the array size should be 20 bytes/4bytes.

string cdown(int param[])
{
    int length = sizeof(param)/sizeof(param[0]);
    cout<<"length: "<< length << endl;

    string blastoff = "blastoff";

    for (int i=0;i<length;i++)
    {
        if (param[i]==0){return blastoff;}

        else
        {
            cout<<param[i]<< " ";
            param[i] = param[i+1];
            param[length-1] = 0;
            cdown(param);
        }
    }
}

int main(void)
{
    int countdown[] = {5,4,3,2,1,};
    cdown(countdown);
    return 0;
}

Result

length: 2
5
length: 2
4
length: 2
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
thxCu
  • 29
  • 2
  • 1
    `param` isn't really an array, it's a pointer, presumably on your platform pointers are 64-bit giving a sizeof of 8 – Alan Birtles Oct 22 '22 at 15:13
  • 1
    to pass arrays to functions, use std::array, or std::vector instead of "old" C-Style arrays. use : `std::string cdown(const std::vector& param)` and then you can use param.size() to get the size of your array. Just out of curiousity who is teaching you C++? (That source too should be updated to at least C++11 coding styles). – Pepijn Kramer Oct 22 '22 at 15:25
  • Thanks @PepijnKramer. I'm in an intro course. Prof. Insisted we learn c++03 to understand why c++11 came to be. We're switching to 11 in the next few weeks – thxCu Oct 22 '22 at 17:00
  • Seems to me he is trying to teach you how steam engines work, to understand electric cars better but well... At least you're learning that handling "C" style arrays is not without its problems. Maybe you can ask him about this for his final C++ lesson : https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines ;) In any case don't forget to have fun learning! – Pepijn Kramer Oct 22 '22 at 17:05
  • *Prof. Insisted we learn c++03 to understand why c++11 came to be.* **Nice**, I was not aware that they are now teaching The History of C++ courses. – Eljay Oct 22 '22 at 17:15
  • `sizeof(array)` will only give the correct size when `array` is actually an array and the type of its elements is `char`. For other element types, the correct form (assuming you in fact have an array and not a mere pointer) is `sizeof(array) / sizeof(array[0])`. – Pete Becker Oct 22 '22 at 17:43

0 Answers0