简体   繁体   中英

how to define a reference to an array in one statement

I define an intermediary typedef in order to define a reference to a fixed size array.

typedef int CI[0x10];
CI& arr=*(CI*)mypointer;

writing it like that it permits me later on to use countof(arr)

I tried to write it in one statement and bellow is my failed attempt. I know that this is wrong as the "&" should be in both "int" and "[0x10]" and not on arr1 but is it possible to write it in one statement ;

int (arr1&)[classInfoN]=*(CI*)mypointer;

You've got the & in the wrong place. It always goes to the left of the identifier, just like your working example.

So:

int (&arr1)[0x10] = *reinterpret_cast<int (*)[0x10]>(mypointer);
// g++ test.cpp -std=c++11
#include <iostream>

int main() {
    int real_arr[0x10] = {1,2,3,4,5,6,7,8,9,0};

    typedef int (&arr_t)[0x10];
    arr_t arr = real_arr;

    for ( auto i = 0; i < 10; ++i ) {
        std::cout << arr[i] << std::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