找到你要的答案

Q:Array of 10 pointer to char[2][2] array

Q:数组10指针到char [ 2 ] [ 2 ]数组

For a pointer to an [2][2] char array, I can write: char (*p)[2][2] and for an array of 10 elements of type pointer to char: char* p[10].

How do you write an array of 10 elements of type pointer to char[2][2]?

Why does this statement have a syntax error?

char (*)[2][2] p[10];

For a pointer to an [2][2] char array, I can write: char (*p)[2][2] and for an array of 10 elements of type pointer to char: char* p[10].

你如何写一个数组的10种类型的指针char [ 2 ] [ 2 ]?

为什么这个语句有语法错误?

char (*)[2][2] p[10];
answer1: 回答1:

You need to use

char (*p[10])[2][2];

But you should really use a typedef, as these decl. can become exceedingly complicated:

typedef char (*ptr_arr)[2][2]; // our pointer-to-char[2][2]
ptr_arr p[10]; // now we have a clean syntax, this is an array of pointers to char[2][2]

You can also use the new using in C++11 like

using ptr_arr = char(*)[2][2];
ptr_arr p[10];

你需要使用

char (*p[10])[2][2];

但你真的应该使用typedef,这些宣言。变得极其复杂:

typedef char (*ptr_arr)[2][2]; // our pointer-to-char[2][2]
ptr_arr p[10]; // now we have a clean syntax, this is an array of pointers to char[2][2]

您还可以使用新的使用C++ 11

using ptr_arr = char(*)[2][2];
ptr_arr p[10];
answer2: 回答2:

You should just use a typedef:

typedef char array[2][2];
typedef array *ptr_to_array[10];

ptr_to_array x; // an array of 10 elements of type pointer to char[2][2]

That way you won't stump all future readers of your code and make them stare at it for a few minutes.

Or, with C++11:

using ptr_to_array = std::array<
                         std::array<std::array<char, 2>, 2>*,
                         10>;

你应该使用typedef:

typedef char array[2][2];
typedef array *ptr_to_array[10];

ptr_to_array x; // an array of 10 elements of type pointer to char[2][2]

这样你就不会让所有未来的读者忘记你的代码,让他们盯着它看几分钟。

或者,用C++ 11:

using ptr_to_array = std::array<
                         std::array<std::array<char, 2>, 2>*,
                         10>;
answer3: 回答3:

If it isn't a requirement that the items are allocated in adjacent memory, then one sound alternative is to put all manners of complex type declarations inside structures:

typedef struct
{
  char array[2][2];
} my_type;

my_type* ptr_array[10];

This have the advantage of not hiding pointers behind typedefs, which is questionable practice in some cases. Particularly when mixing pointers and arrays, since arrays will decay into a pointer to the first element whenever used in an expression.

(If items must be allocated adjacently, then you can still use this method, but you need to kill struct padding with some non-standard mechanism such as #pragma pack(1))

如果不是在相邻内存中分配项的要求,那么一个合理的选择就是将复杂类型声明的所有方式放入结构中:

typedef struct
{
  char array[2][2];
} my_type;

my_type* ptr_array[10];

这有没有隐藏指针类型背后的优势,这在某些情况下是有问题的做法。特别是当混合指针和数组时,数组将在表达式中使用时,会变成指向第一个元素的指针。

(如果项目必须分配相邻,那么你仍然可以使用这个方法,但是你需要用一些不规范的机构如# pragma包杀结构填充(1))

c  arrays  pointers