Pointer to Struct

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int num;
    char *name;
    char sex;
    float score;
} STU;

int main()
{
    int i;
    STU Student0; /* a STU variable */
    STU * Student1 = NULL; /* a pointer to a STU variable  */
    STU * Student2 = NULL; /* a pointer to a 1D STU array */
    STU ** Student3 = NULL; /* a pointer to a pointer to STU variable */
    STU ** Student4 = NULL; /* a pointer to a 2D STU array */

    /* initialize STUDENT0 */
    Student0.num=122;
    Student0.name= "zhang ping";
    Student0.sex='M';
    Student0.score=99.2;
    /* can't use Student0={102,"Zhang ping",'M',78.5}
    You can use STU Student0={102,"Zhang ping",'M',78.5} */;

    /* a pointer to a STU variable */
    Student1=&Student0;

    /* a pointer to  a 1D STU array (1*3)*/
    Student2 = (STU *) calloc(3, sizeof(STU));

    /* a pointer to a pointer to STU variable */
    Student3=&Student1;

    /* a pointer to to a 2D STU array (3*3) */
    Student4 = (STU **) calloc(3, sizeof(STU *));
    for (i=0; i<3; i++)
    {
        Student4[i] = (STU *) calloc(3, sizeof(STU));
    }

    Student1->num=2;
    Student1->name= "zhang ling2";
    (*Student1).sex='f';
    (*Student1).score=99.2;

    /*(col 2) allocate value */
    (Student2+1)->num=3;
    (*(Student2+1)).name="zhang cai";
    Student2[1].sex='f';
    Student2[1].score=99.5;

    (*Student3)->num=4;
    (*Student3)->name= "zhang ling4";
    (**Student3).sex='m';
    (**Student3).score=99.3;

    /* (col 3 row 2) allocate value */
    Student4[2][1].num=5;
    Student4[2][1].name="zhang cai2";
    Student4[2][1].sex='f';
    Student4[2][1].score=99.6;

    /* Free memory */
    free(Student1);
    free(Student2);
    free(Student3);
    free(Student4);
    return 0;
}

 

Updated: 2016-07-01 — pm3:33

Leave a Reply

  Subscribe  
Notify of