Docstoc

Structures

Document Sample
Structures Powered By Docstoc
					           Structures




11/23/03                1
               Structures
• A means of storing related variables of
  possibly different types together.
• A new (compound) data type.
• In Java and C++ both variables and
  functions (called methods) are stored
  together and called a class.
• In database languages a structure would be
  called a record.
11/23/03                                       2
           Structure Declaration

                            called members
struct tag {
   type variable;
                           optional (but need at
   type variable;          least one).
   …
} variable, variable, …;

11/23/03                                           3
              Specific Example
struct course {
   char * dept;       /* e.g. "cs" */
   char * title;      /* e.g. "Intro to C Programming"*/
   int number;        /* e.g. 151 */
   int section;       /* e.g. 1 */
};
• This defines a type only (struct course), no memory used
   or variables defined. This is not a declaration!!


 11/23/03                                                4
            Variables of type 'course'
struct course {
   char * dept;     /* e.g. cs */
   char * title;    /* e.g. Intro to C Programming*/
   int number;      /* e.g. 151 */
   int section;     /* e.g. 3 */
} c1, c2, c3;
Defines and Declares three 'course-type' variables.



 11/23/03                                              5
     Assigning to and using structs
c1.dept = "cs"; /* called 'dot' notation */
c1.title = "Intro to C Programming";
c1.number = 151;
c1.section = 1;
printf(“%s %s %d %d\n”, c1.dept, c1.title,
  c1.number, c1.section);
cs Intro to C Programming 151 1
11/23/03                                      6
   Separating type and declaration
struct course {    /* this defines the new 'struct course' type */
   char * dept;    /* e.g. cs */
   char * title;   /* e.g. Intro to C Programming*/
   int number;     /* e.g. 151 */
   int section;    /* e.g. 3 */
};

struct course courses[100]; /* an array (collection) of 100 courses */
courses[0].dept = “English”;      /* note syntax */
courses[1].dept = “Psychology”; /* etc. */


11/23/03                                                                 7
              The memory picture
                           &c.suit
       struct card {                c:   123456
          char *suit;                       10
                           &c.val
          int val;
       } c;
                             123456:         c
       c.suit = "clubs";                     l
       c.val = 10;                           u
                                             b
                                             s
                                             \0


11/23/03                                          8
                    Variations
• The tag is not needed if separate
  declarations are not used.
     struct {
       char * name;
       char *tel_no;
     } tel_list[100]; /* list of 100 names & telnos */
• Cannot declare other variables of this type
  (because no tag).
11/23/03                                                 9
Need either tag or variable or both
     struct {
        char * name;
        char *tel_no;
     };
• This is useless -- no variables of this type
  and no tag to use to declare variables.



11/23/03                                         10
                     typedef
• A way of giving meaningful names to
  existing types.
typedef old_type new_type_name;
• Can be used to rename all current types.
• char, int, float, double, struct, and pointers
  to these.
• Mostly used with struct type

11/23/03                                           11
           Using typedef with structs
typedef struct {
    char * dept;
    char * title;
    int number;
    int section;
} course_t; /* course_t is new type and can be used in declarations */
int main(void) {
    course_t cs151, cs161, cs162; /* declares 3 courses */
    cs151.title = "Introduction to C Programming";
    etc.


11/23/03                                                             12
               Typedef or Tag?
typedef struct {          struct course {
   char * dept;               char * dept;
   char * title;              char * title;
   int number;                int number;
   int section;               int section;
} course_t;               };

/* 'course_t' is type*/   /* 'struct course' is type*/
course_t c1, c2, c3;      struct course c1, c2, c3;



11/23/03                                                 13
                    Nested structs
typedef struct {int x, y;} point_t;
typedef struct {point p1, p2;} line_t;

int main(void) {
   line_t ln1;
   ln1.p1.x = 10;     /* line starting point */
   ln1.p1.y = 5;
   ln1.p2.x = 30;     /* line ending point */
   ln1.p2.y = 10;
   etc.
11/23/03                                          14
                      Pointers to structs
           typedef struct {
               char * dept; char * title;
               int number; int section;
           } course_t;

           int main(void ) {
               course_t c, *p;
               p = &c;
                    /* dept member in struct pointed to by p */
               p->dept = "cs";
               p->number = 151;                         prints:
               printf("%s %d", c.dept, c.number);       cs 151
               return 0;
           }
11/23/03                                                          15
           Passing structs to functions.
• Both structs and pointers to
  structs can be passed to a
  function.
• Since structs may contain lots
  of data, passing the pointer is
  more efficient.


11/23/03                                   16
           print_card -- uses by-value
typedef struct {    /* note: comes before print_card prototype */
        char * suit;
        int val;
   } card_t;
                 /* function prototype uses 'card' type */
void print_card(card_t c);

int main(void) {
    card_t c = {"clubs", 10}; /* note: initialization! */
    print_card(c);                 /* call by value */
    return 0;
}

void print_card(card_t c) { /* this c is a copy of the c in main */
   printf("%d of %s\n", c.val, c.suit);
}
11/23/03                                                              17
      init_card -- uses by-reference
typedef struct { char * suit; int val; } card_t;
void print_card(card_t c);
void init_card(card_t *p, char * suit, int val);
int main(void) {
    card_t c;
    init_card(&c, "clubs", 10);   /* call by reference */
    print_card(c);                /* call by value */
    return 0;
}
void print_card(card_t c) {
    printf("%d of %s\n", c.val, c.suit);
}
void init_card(card_t *p, char * suit, int val){ /* p points to c in main */
    p->suit = suit;
    p->val = val;
}

11/23/03                                                                  18
    Whole structs can be assigned.
int main(void) {

    card_t c, d;
    init_card(&c, "clubs", 10);
    d = c;       /* This works! Data in c copied to d*/
    print_card(d);

    return 0;
}

11/23/03                                                  19
           A C-language anomaly
• Can’t assign one string to another but works
  if in a structure.
    typedef struct{char s[80]; } string_t;
    string_t s1={"Go Beavers!"}, s2;
    s2 = s1;    /* copies the array from s1 to s2 */
    printf("%s", s2.s); /* prints "Go Beavers!" */




11/23/03                                               20
           StudentStat.c, an example
•   Define a structure to hold student info.
•   Fill the struct with data from a file.
•   Calculate a class average grade.
•   Print the list of students and the ave grade.




11/23/03                                            21
                     The structure
typedef struct {
        char last[30];
        char first[30];
        char grade[2];
} student_t;




11/23/03                             22
            class = array of students
int main (void) {
    float ave = 0;
    student_t class[MAX_CLASS_SIZE]; /* an array of students */
    int n; FILE *fp;

    if((fp =fopen("data.txt", "r")) == NULL){ /* open the file */
            printf("Couldn't open file");
            exit(1);
    }
    n = read_data(fp, class, MAX_CLASS_SIZE); /* read into 'class' array */
    calc(class, n, &ave);                 /* find the class average */
    list_students(class, n);              /* list the students */

    printf("\nClass average = %.1f", ave); /* and print the average */
    fclose(fp);
    return 0;
}


11/23/03                                                                      23
                            read_data
int read_data(FILE *fp, student_t *p, int n) {
    int i;

    for(i=0; i < n; ++i, ++p) {       /* read up to n records */
          fscanf(fp, "%s %s %s", /* store in student struct */
                   p->last, p->first, p->grade);
          if(*p->last == '-')         /* quit if last starts with '-' */
                   break;
    }                                 /* else move to next record */
    return i;
}




11/23/03                                                                   24
                                calc
void calc(student_t *p, int n, float *p_ave) {
   int i;
   float grade_points[] = {4,3,2,1,0,0}; /* note 0 for grade 'E' */

    for(i=0; i < n; ++i, ++p)
                   /* sum the grades */
          *p_ave = *p_ave + grade_points[*p->grade - 'A'];
    *p_ave = *p_ave/n; /* and find average */

    return;
}

11/23/03                                                              25
                       list_students
void list_students(student_t *p, int n) {
   int i;

    for(i=0; i < n; ++i, ++p)
          printf("%-12s %-10s %-3s\n", /* one student per line */
                   p->first, p->last, p->grade);
    return;
}




11/23/03                                                            26
                program list
Cards.c
StudentStat.c




11/23/03                       27

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:14
posted:9/19/2011
language:English
pages:27