How to get size c++ dynamic array

前端 未结 5 1941
南方客
南方客 2020-12-02 02:31

I\'m studying C++ and I need to create structure Airplane and work with it.

My structure Airplane.h

#include \"stdafx.         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 02:51

    One approach that i use when i work with dynamic arrays, is to pass the array as a reference to the function. This will help you to keep the size information of the array.

    For Example:

    string list1[3] = {
        "item1",
        "item2",
        "item3"
    };
    
    string list2[2] = {
        "item1",
        "item2"
    };
    
    template
    void PrintItems(T(&items)[N]) {
        for (int i = 0; i < N; i++) {
            cout << items[i] << endl;
        }
    }
    
    int main() {
        PrintItems(list1);
        PrintItems(list2);
    }
    

    In the previous example, N stores the correct size information for the array. More information here

提交回复
热议问题