Skip to main content
Engineering LibreTexts

10.2: Pointers and Structures

  • Page ID
  • It is generally not a good practice to send entire structures to functions as arguments. The reason is because you wind up copying a lot of data. The transistor structure above contains three doubles at 8 bytes each, a short int at 2 bytes, and 20 bytes for the char array, leaving a total of 46 bytes of memory that need to be copied if we pass this to a function. It would be much more efficient if we simply passed the starting address of the structure to the function. That is, we tell the function where to find the structure by using a pointer (this is called “passing by reference” versus the more familiar “passing by value”). This is why we declared ptransistor. We initialize it like so:

    ptransistor = &my_transistor;

    To access the various fields, we can no longer use the period because we no longer have a struct transistor; we have a pointer to one. For pointers, we access the fields via the pointer token, which is made up of a dash followed by a greater than sign: -> Thus, we might say:

    ptransistor->currentgain = 200.0;
    strcpy( ptransistor->model, “2N3904” );

    Below is a function that simply prints out the values of the various fields.

    void print_transistor( struct transistor *pt )
        printf(“For model: %s\n”, pt->model );
        printf(“Current gain is %lf\n”, pt->currentgain );
        printf(“Breakdown voltage is %lf\n”, pt->breakdown );
        printf(“Maximum power is %lf\n”, pt->maxpower );
    /* note use of %s for string and %lf for “long float” i.e., double */

    We pass the function a pointer to a transistor structure like so:

    print_transistor( &my_transistor );
    /* we could also use print_transistor( ptransistor );
       if we initialized it as above */