开发者

int (*p) [4]?

int (*p) [4] ;

Is "p" pointer to 开发者_开发问答array of 4 integers ?? or what ??

and How can I call "new" for this pointer ??


Is "p" pointer to array of 4 integers?

Correct!

How can I call "new" for this pointer?

For example, p = new int[7][4].


int (*p)[4] is, indeed, a pointer to an array of four ints.

You can dynamically allocat an object of type "pointer to array of four int" as follows.

int (**ptr)[4] = new (int (*)[4]);

Note, no space for any ints is allocated; only the pointer itself.

You can allocated an array of 4 ints as follows:

int *ptr = new int[4];

What you can't do (without explicit casting) is assign a pointer to a dynamically allocated array of 4 int to a pointer of type int (*)[4]. Whenever you allocate an array via new, even if you use a typedef, the type of the new expression is a pointer to the first element of the array; the size of the array is not retained in the type of the new expression.

This is because new[] expressions can allocate arrays where the size of the array is chosen at runtime so would not always be possible (or even desirable) to encode the array size into the type of the new expression.

As has been suggested, you can dynamically allocate an array of one array of 4 int. The size of the first array is lost from the type information and what you get is a pointer to the first element of the array (of size 1) of the arrays of four int.

int (*p)[4] = new int[1][4];

Even though it is an array of just 1 (arrays of 4 int), you still need to use delete[] to deallocate p.

delete[] p;


The online CDECL evaluator is a helpful resource for questions like this:


cdecl

C gibberish ↔ English

int (*p)[4];

    declare p as pointer to array 4 of int
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜