quantum231
quantum231

Reputation: 2585

C++: What is the difference between int *x[5] and int (*x)[5]?

Do they both mean the same thing? Does their meaning differ between C and C++?

Upvotes: 3

Views: 2498

Answers (4)

dguan
dguan

Reputation: 1033

In C and C++, the 2 declarations meaning does not change. In C and C++ declarations, '[]' has higher priority than '*' when combining with variables. So, in int * x[5] declaration, x is combined with [5], so it is an 5 element array of int*. In int (*x)[5] declaration, however, x is forced to combine with '*' by use of '()', so now x is a pointer to int[5].

Upvotes: 2

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

Use the right-left rule.

Start at the variable declaration -- x.

Now read right until you run into a top-level ,, a ; or an unbalanced closing ) or the end of the declaration.

Read left until you find the matching (. Repeat from the start.

x) // x
(*x) // is a pointer to
(*x)[5]; // an array of 5 elements
int (*x)[5]; // of integers

x[5]; // x is an array of 5 elements
*x[5]; // of pointers to
int *x[5]; // integers

Simple!

Upvotes: 5

Van Tr
Van Tr

Reputation: 6103

They are not same:

int * a[5] is an array of five elements, each element is an int pointer.

int (*a)[5] is a pointer to an array, this array contain five int elements.

This meaning is same in c and c++.

For fast, using http://cdecl.org/ (not recommended)

For understanding, read How to interpret complex C/C++ declarations (recommended)

Upvotes: 3

Jonathan Wakely
Jonathan Wakely

Reputation: 171263

You can answer this kind of question for yourself using http://cdecl.org/ (paste in the type and it tells you what it means in English).

Do they both mean the same thing?

No.

Does their meaning differ between C and C++?

No.

int* a[5] is an array of five pointers to int.

int (*a)[5] is a pointer to an array of five ints.

Upvotes: 6

Related Questions