Help understand pointer declaration

Let's consider the pointer declaration:

 
int *x;

This is understood as *x is of type int and so x is a pointer.

So, how would you explain it in the same way for this pointer declaration below:
 
char (* ptr)[3]


I know the way to read it as "ptr is pointer to such one dimensional array of size three which content char type data" but I just wonder about how would you explain it as the way of int *x.
You could think of dereferencing a pointer as taking away a '*' from the type.

For instance:

int* x;

x is of type int*. Dereference x by doing *x and you get the type int.

For

char (*ptr)[3]

ptr is of type char (*)[3]. Dereference ptr by doing *ptr and you get the type char [3].
Last edited on
Thanks! This is interesting way to look at it.
How about this one?

float (* ptr)(int)
Let's me try that:

ptr is of type float (*) (int). Deference ptr by doing *ptr and you get the type float (int).
So ptr is a pointer to a function whose parameter is int type and return a float.

And this one seems very complicated.

int ( * ( * ptr ) [ 5 ] ) ( )

How would you do that?
> And this one seems very complicated.
> int ( * ( * ptr ) [ 5 ] ) ( )
> How would you do that?

Ideally, we wouldn't do that at all.
Instead, we would use type aliases or typedefs to make it less complicated, more easily understandable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <type_traits>

int main()
{
    using function_type = int() ; // nullary function returning int
    typedef int function_type() ; // same as above

    using ptr_function_type = function_type* ; // pointer to function_type
    typedef function_type* ptr_function_type ; // same as above

    using array_type = ptr_function_type[5] ; // array of 5 ptr_function_type
    typedef ptr_function_type array_type[5] ; // same as above

    using ptr_array_type = array_type* ; // pointer to array_type
    typedef array_type* ptr_array_type ; // same as above

    static_assert( std::is_same< int( * (*)[5] )(), ptr_array_type >::value, "must be the same type" ) ;

    int ( * ( * ptr ) [ 5 ] ) ( ) = nullptr ;
    ptr_array_type ptr2 = ptr ;
    static_assert( std::is_same< decltype(ptr), decltype(ptr2) >::value, "must be of the same type" ) ;
}

http://coliru.stacked-crooked.com/a/65b83759e0eb82cf
Thanks! This is really new and look chinese to me!
I need to read up about this now.
Topic archived. No new replies allowed.