简体   繁体   中英

C++ 98 array size

I'm just wondering if there is a way to allocate size of array without specifying it in C++98.

For example, this is code from C++11 that works fine:

int main(){
    int array[]={12,3124,126,35742,3,41234,2};
    for (int var: array){
        cout << var << endl;
    }
    return 0;
}

But can I do it in C++98 or do I have to specify the array size?

int main(){
    int array[]={12,3124,126,35742,3,41234,2};
    for (int i=0; i<array.size ; i++){
        cout << array[i] << endl;
    }
    return 0;
}

Sure. You can make a template function which takes an array by reference and deduces the size, then returns that.

template<typename T, size_t N>
size_t array_size(T(&)[N]) {
    return N;
}

int main(){
    int array[]={12,3124,126,35742,3,41234,2};
    for (size_t i=0; i<array_size(array); i++){
        cout << array[i] << endl;    
    }
}

One good thing about this method over using sizeof(array)/sizeof(array[0]) , is that it will not give you an incorrect answer if array is actually a pointer. It will simply fail to compile.

I don't know about that array.size thing you reference, but this would suffice.

int main()
{

    int array[]={12,3124,126,35742,3,41234,2};

    for (int i=0; i < sizeof(array)/sizeof(array[0]); i++)
    {
        cout << array[i] << endl;
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM