Why does it redefine a pointer to a struct?

Discussion in 'C Programming' started by fl, Feb 7, 2014.

  1. fl

    fl Guest

    Hi,
    I find the following definition from a company provided header file. The sample application software still uses FIR16, not *FIR16_handle.

    The typedef line really puzzles me. Could you explain it to me? It would be better to give a small example.


    Thanks,




    typedef struct {
    long *coeff_ptr; /* Pointer to Filter coefficient */
    long * dbuffer_ptr; /* Delay buffer ptr */
    int cbindex; /* Circular Buffer Index */
    int order; /* Order of the Filter */
    int input; /* Latest Input sample */
    int output; /* Filter Output */
    void (*init)(void *); /* Ptr to Init funtion */
    void (*calc)(void *); /* Ptr to calc fn */
    }FIR16;

    /*---------------------------------------------------------------
    Define a Handles for the Filter Modules
    -----------------------------------------------------------------*/
    typedef FIR16 *FIR16_handle;
     
    fl, Feb 7, 2014
    #1
    1. Advertisements

  2. fl

    Joe Pfeiffer Guest

    We just had quite a thread on typedefs! Reviewing that wouldn't be a
    bad idea. Anyway, some programmers prefer to hide the syntax for
    structs and pointers by using typedefs.

    So if you were to declare

    FIR16 john;

    you'd be declaring an instance of the struct up there, and you could get
    at its fields by saying things like

    john.input = 42;

    You can also declare a pointer to this struct by saying something like

    FIR16 *paul;

    and use it with things like

    paul = malloc(sizeof *paul);
    paul->input = 42;

    Also, because of the second typedef, a FIR16_handle is another name for
    a pointer to a FIR16, so you could say things like

    FIR16_handle george;

    george = malloc(sizeof *george);
    george->input = 42;

    It's a little unusual (in my experience) to see a handle typedef and a
    struct definition both in a header file. Most of the time when I see
    somebody want to call something a handle, they want to make it opaque.
    In these cases, all that would appear in your header file would be

    typedef FIR16 *FIR16_handle;

    the struct definition would be internal to the library you're using, and
    the only way to access elements of the struct would be through
    library-supplied functions.
     
    Joe Pfeiffer, Feb 8, 2014
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.