Triple pointers in C: is it a matter of style?

后端 未结 5 1157
生来不讨喜
生来不讨喜 2020-12-04 20:18

I feel like triple pointers in C are looked at as \"bad\". For me, it makes sense to use them at times.

Starting from the basics, the single pointer

5条回答
  •  忘掉有多难
    2020-12-04 21:03

    So what are some of the conventions out there? Is this really just a question of style/readability combined with the fact that many people have a hard time wrapping their heads around pointers?

    Multiple indirection is not bad style, nor black magic, and if you're dealing with high-dimension data then you're going to be dealing with high levels of indirection; if you're really dealing with a pointer to a pointer to a pointer to T, then don't be afraid to write T ***p;. Don't hide pointers behind typedefs unless whoever is using the type doesn't have to worry about its "pointer-ness". For example, if you're providing the type as a "handle" that gets passed around in an API, such as:

    typedef ... *Handle;
    
    Handle h = NewHandle();
    DoSomethingWith( h, some_data );
    DoSomethingElseWith( h, more_data );
    ReleaseHandle( h );
    

    then sure, typedef away. But if h is ever meant to be dereferenced, such as

    printf( "Handle value is %d\n", *h );
    

    then don't typedef it. If your user has to know that h is a pointer to int1 in order to use it properly, then that information should not be hidden behind a typedef.

    I will say that in my experience I haven't had to deal with higher levels of indirection; triple indirection has been the highest, and I haven't had to use it more than a couple of times. If you regularly find yourself dealing with >3-dimensional data, then you'll see high levels of indirection, but if you understand how pointer expressions and indirection work it shouldn't be an issue.


    1. Or a pointer to pointer to int, or pointer to pointer to pointer to pointer to struct grdlphmp, or whatever.

提交回复
热议问题