Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ asterisk and bracket operators used together

Tags:

c++

operators

Sorry for the crappy title, but I don't know how to better describe this problem.

What is the meaning of:

int (*x)[];

and how to initialize it?

I know it isn't int *x[] since:

int a,b;
int (*x)[] = {&a, &b};

won't compile.

Thank you in advance.

like image 880
Chlind Avatar asked Apr 27 '12 12:04

Chlind


People also ask

What does the asterisk do in C?

In computer programming, a dereference operator, also known as an indirection operator, operates on a pointer variable. It returns the location value, or l-value in memory pointed to by the variable's value. In the C programming language, the deference operator is denoted with an asterisk (*).

What is double asterisk in C?

It declares a pointer to a char pointer.

What is the use of square brackets [] in C language?

Square brackets are used to index (access) elements in arrays and also Strings.

What does the -> operator allow you to do with respect to pointers to objects?

The "arrow" operator -> is used to dereference pointers to objects to get their members. So if you have a pointer an object in the variable ui and the object has a member pushButton then you can use ui->pushButton to access the pushButton member.


2 Answers

Type declarations have an expression-like syntax, so you parse them as you would an expression:

      x       x is
     *x       a pointer
    (*x)[]    to an array of unknown dimensions
int (*x)[]    of int

The precedence rule is that the operators to the right bind tighter than those to the left, in each case, the operator closer to the element binds tighter, and finally, that parentheses can be used to change these bindings, so:

int  *x[];    is an array of pointers,
int *(x[]);   as is this.
int (*x)[];   whereas here, the parentheses change the bindings.
like image 90
James Kanze Avatar answered Sep 20 '22 17:09

James Kanze


Using cdecl, you can easily determine the type:

declare x as pointer to array of int

So you can initialize x with the address of an array:

int a[]; // conceptual: error if compiled
x = &a;

Note that the size of the array is part of its type, so you cannot assign the address of an array of size N to a pointer to array of size M, where N!=M (this is the reason for the error above: you need to know the size of the array to declare it)

int b[5];
int c[6];
int (*y)[6];
y = &b; // error
y = &c; // OK
like image 27
Attila Avatar answered Sep 20 '22 17:09

Attila