Sizeof() on a C++ array works in one function, but not in the other

后端 未结 3 527
谎友^
谎友^ 2020-12-21 16:25

I\'m trying to learn more about arrays since I\'m new to programming. So I was playing with different parts of code and was trying to learn about three things, sizeof(

3条回答
  •  猫巷女王i
    2020-12-21 17:26

    What you've encountered was array-to-pointer conversion, a C language feature inherited by C++. There's a detailed C++-faq post about this: How do I use arrays in C++?

    Since you're using C++, you could pass the array by reference:

    template
    void arrayprint(int (&inarray)[N])
    {
        for (int n_i = 0 ; n_i < (sizeof(inarray) / sizeof(int)) ; n_i++)
            cout << inarray[n_i] << endl;
    }
    

    although in that case the sizeof calculation is redundant:

    template
    void arrayprint(int (&inarray)[N])
    {
        for (size_t n_i = 0 ; n_i < N ; n_i++)
            cout << inarray[n_i] << '\n';
    }
    

    And, as already mentioned, if your goal is not specifically to pass a C array to a function, but to pass a container or a sequence of values, consider using std::vector and other containers and/or iterators.

提交回复
热议问题