Pointer and Struct Tutorial (revision 120925-r04KI)

Return to Lab 03

  • Create a program named cobapointerstruct.c with almost the same content with the previous tutorial. Change YOUR_ID with your student ID. CHange TOKEN with your token.
    $ vi cobapointerstruct.c

    // YOUR_ID was here!
    // ZCZC TOKEN
    
    #include<stdio.h>
    
    typedef struct person
    {
       char *name;
       int age;
    } PERSON;
    
    int main()
    {
       PERSON pp;
       pp.name = "John Smith";
       pp.age = 25;
       printf("%s\n",pp.name);
       printf("%d\n",pp.age);
       return 0;
    }
  • In this program, struct PERSON pp initiated to be a variable, so that all general operations that can be done to a variable will be applicable to PERSON, including creating pointer to PERSON variable just like what we've done in Pointer Introduction Tutorial.
  • Modify cobapointerstruct.c, add variable char *address and char *phone into struct PERSON so that there are 4 variables, name, age, address and phone. Initiate those two additional variables in main method with content below:
    address="Jalan Carita no. 25 Kukusan Depok"
    phone="02145187543"
    Print both variables using printf just like name and age.
  • Save your work and exit from vi. compile your program to create cobapointerstruct executable. Run it.
    :wq
    $ gcc -o cobapointerstruct cobapointerstruct.c
    $ ./cobapointerstruct

    John Smith
    25
    Jalan Carita no. 25 Kukusan Depok
    02145187543
  • Now add a pointer variable PERSON *pptr which will refer to the address of PERSON p.
    PERSON *pptr;
    pptr = &pp;
  • To be able to access and modify the variables inside PERSON pp from pointer PERSON pptr, we have to use *(->) NOT (.). For example, we will change the previous code that access name variable:
    pp.name = "John Smith";

    will become
    pptr->name = "John Smith";

    Change all the 4 variables access codes (name, age, address and phone) inside cobapointerstruct.c to be just like the example above.
  • If we want to access the content of struct PERSON pp from pointer PERSON pptr, we have to use *(->) sign, for example:
    printf("%s\n",pp.name);

    is replaced with
    printf("%s\n",pptr->name);

    Change all the 4 variabless access codes inside.
  • Save and recompile your work.
    :wq
    $ gcc -o cobapointerstruct cobapointerstruct.c
  • Run pointerstruct executable and record the output into cobapointerstruct.txt.
    ./cobapointerstruct > cobapointerstruct.txt
  • The content of cobapointerstruct.txt must be the same with below:
    $ cat cobapointerstruct.txt

    John Smith
    25
    Jalan Carita no. 25 Kukusan Depok
    02145187543
  • This marks the end of Pointer and Struct Tutorial.

Return to Lab 03
Return to Wiki