简体   繁体   中英

How to declare of array of pointers to 2D arrays

I have a list of 2D arrays:

float a[][9] = { ... }
float b[][9] = { ... }
float c[][9] = { ... }

I want to have another array of pointers that point to each of the 2D arrays, like this:

what_should_be_here?? arr[] = { a, b, c }

How to achieve this?

Use typedef to simplify declaration. Each of the element of arr is float (*)[9] . Say this type is SomeType . Then {a,b,c} means you need an array of three elements of type SomeType .

SomeType arr[] = {a,b,c};

Now the question is, what is SomeType ? So here you go:

typedef float (*SomeType)[9]; //SomeType is a typedef of `float (*)[9]`

SomeType arr[] = {a,b,c}; //this will compile fine now!

As I said, use typedef to simplify declaration!

I would choose a better name for SomeType :

typedef float (*PointerToArrayOf9Float)[9];

PointerToArrayOf9Float arr[] = {a,b,c}; 

That is a longer name, but then it makes the code readable!

Note that without typedef, your code will look like this:

float (*arr[])[9] = {a,b,c};

which is UGLY. That is why I will repeat:

Use typedef to simplify declaration!

Hope that helps.

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