Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do parentheses in a C variable declaration mean?

Tags:

c

syntax

Can someone explain what this means?

int (*data[2])[2]; 
like image 461
Andrew Avatar asked Oct 28 '08 20:10

Andrew


People also ask

Do parentheses work in C?

Parentheses are used in C expressions in the same manner as in algebraic expressions.

What do parentheses represent?

Parenthesis definition Parenthesis refer to punctuation marks "(" and ")" used to separate relevant information or a comment from the rest of the text, or to enclose mathematical symbols, or the text inside of these marks. The punctuation marks in the math equation 2x(4+6) are an example of parenthesis. noun.

What is parentheses in C Plus Plus?

Valid Parentheses in C++ The expression has some parentheses; we have to check the parentheses are balanced or not. The order of the parentheses are (), {} and []. Suppose there are two strings. “()[(){()}]” this is valid, but “{[}]” is invalid. The task is simple; we will use the stack to do this.


2 Answers

What are the parentheses for?

In C brackets [] have a higher precedence than the asterisk *

Good explanation from Wikipedia:

To declare a variable as being a pointer to an array, we must make use of parentheses. This is because in C brackets ([]) have higher precedence than the asterisk (*). So if we wish to declare a pointer to an array, we need to supply parentheses to override this:

double (*elephant)[20]; 

This declares that elephant is a pointer, and the type it points at is an array of 20 double values.

To declare a pointer to an array of pointers, simply combine the notations.

int *(*crocodile)[15]; 

Source.

And your actual case:

int (*data[2])[5]; 

data is an array of 2 elements. Each element contains a pointer to an array of 5 ints.

So you you could have in code using your 'data' type:

int (*data[2])[5]; int x1[5]; data[0] = &x1; data[1] = &x1;  data[2] = &x1;//<--- out of bounds, crash data has no 3rd element int y1[10]; data[0] = &y1;//<--- compiling error, each element of data must point to an int[5] not an int[10] 
like image 150
Brian R. Bondy Avatar answered Oct 03 '22 11:10

Brian R. Bondy


There is a very cool program called "cdecl" that you can download for Linux/Unix and probably for Windows as well. You paste in a C (or C++ if you use c++decl) variable declaration and it spells it out in simple words.

like image 20
Paul Tomblin Avatar answered Oct 03 '22 11:10

Paul Tomblin