The principle of priority understanding of time char (* p) [sizeof (c)];

I study pointers and challenge myself. I tried to dereference a pointer to an array of characters. In the end, it worked:

char (*p)[sizeof(c)]; 

Where c is an array of c [] = "something"

It’s hard for me to understand how (*p)[sizeof(c)]; different from *p[sizeof(c)];

Based on what I currently know (which is not enough!), The computer says this in the case of (*p)[sizeof(c)]; :

"p points to c! oh, and btw, p is an array of any sizeof (c) value ending with".

But even this seems strange to me, so I think I'm confused by what is created when the brackets are added.

Can someone explain?

Full code in context:

 #include <iostream> using namespace std; int main(int argc, char *argv[]) { char c[] = "something"; char (*p)[sizeof(c)]; // this works // char *p[sizeof(c)]; // this doesn't? p = &c; cout << p << endl; cout << *p << endl; } 
+6
source share
4 answers

Types in C can be read with what is informally known as a rule from right to left. You start with the name of the variable being declared, then go straight when you can, then go left when you can, and start again. The brackets stop you until all of their content has been reviewed.

In your example:

 char (*p)[sizeof(c)]; ^ p... (hit ')', turn around) ^ is a pointer... (hit '(', turn around and remove '()') ^^^^^^^^^^^ to an array of `sizeof(c)`... (end of line, turn around) ^^^^ chars. nothing left, we're done! 

Without parentheses, this becomes:

 char *p[sizeof(c)]; ^^^^^^^^^^^^ p is an array of `sizeof(c)`... (end of line, turn around) ^^^^^^ pointers to char. 

Which is really quite different.

+14
source

In this definition

 char (*p)[sizeof(c)]; 

you define the variable p, which is a pointer (the contingent of brackets is evaluated first) for an array of characters with a size of [sizeof c]. At this point, your p code does not indicate anything specific, since it has not yet been initialized.

With a different definition

 char *p[sizeof(c)]; 

you define a variable p, which is an array (* evaluated later) of pointers to a character.

you have a pointer to an array against an array of pointers.

+1
source

Job Type Mismatch

 p = &c; 

- a problem.

c is an array of 10 characters, and &c is a pointer to an array of 10 characters.

In char (*p)[sizeof(c)]; , p is a pointer to a character array sizeof(c) (10). So it matches type &c .

In char *p[sizeof(c)]; , p is an array of pointers sizeof(c) (10). But this does not match type &c .

+1
source

The priority principle is simple - postfix operators have a higher priority than the prefix. * is the prefix operation, and [sizeof(c)] is the postfix, so when you say:

 char *p[sizeof(c)]; 

same as

 char *(p[sizeof(c)]); 

a statement with a higher priority is first associated with the operand (here the name of the declarator is p ).

0
source

Source: https://habr.com/ru/post/1013572/


All Articles