typedef , arrays, pointers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bash b
    New Member
    • Jan 2011
    • 1

    typedef , arrays, pointers

    1)I am reading a code and I want to know the meaning of the following code:

    Code:
    typedef unsigned int e;
    typedef unsigned int* r;
    typedef unsigned int** a;
    typedef unsigned int*** b;
    typedef unsigned int**** t;
    2)what does it mean having 1, 2, 3 or 4 stars attached to the int or having them atached to the variable for example int **a and int** a.

    3)Is it true that int ****t is equivalent to int ***t[] and if this correct what about int *t?
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    In general, you can read declarations from right to left. Translate each star into the phrase "is a pointer to". Translate "typedef" into "is a synonym for" and insert that phrase immediately after the variable name.

    Line 1: e is a synonym for unsigned int.
    Line 2: r is a synonym for pointer to an unsigned int.
    Line 3: a is a synonym for pointer to a pointer to an unsigned int.
    Line 4: b is a synonym for pointer to a pointer to a pointer to an unsigned int.
    Line 5: t is a synonym for pointer to a pointer to a pointer to a pointer to an unsigned int.

    What's with all this pointer-to-a-pointer stuff? For example, these pointer variables can be initialized as follows. (Notice that the digit I chose to use in the variable names matches the number of stars in the corresponding typedef.)
    Code:
    e v;
    r v1;
    a v2;
    b v3;
    t v4;
    
    v1 = &v;
    v2 = &v1;
    v3 = &v2;
    v4 = &v3;
    Here's how you could set v to zero using each of these variables (assuming the pointers are initialized as shown above):
    Code:
    v = 0;
    *v1 = 0;
    **v2 = 0;
    ***v3 = 0;
    ****v4 = 0;
    It is certainly possible to use high levels of indirection (lots of stars), but I rarely find it useful enough to be worth the confusion. I use one-star indirection every day. I use two-star indirection every so often. I've used three-star indirection a few times in 20+ years. I don't think I've ever used four-star (or higher) indirection.

    Comment

    Working...