04-structs

04-structs - CPE 357 - Systems Programming Fall 2009, Day 4...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CPE 357 - Systems Programming Fall 2009, Day 4 Structs and Memory Model Last Modified: Mon Sep 28 11:23:50 PDT 2009 Structs: Example: struct planet { char name[30]; double distance; // km int order; } mercury, venus; // optional structure tag. // optional variable names. struct planet mars, jupiter; struct planet earth = {"earth", 150e6, 3}; mars.order = 4; mars.distance = 230e6; strcpy(mars.name, "mars"); struct planet orb; orb = earth; struct planet *orbptr; orbptr = &orb; struct planet *pptr; orbptr = &venus; orb.order = 4; orbptr->distance = 108e6; strcpy(orbptr->name, "venus"); *pptr = *orbptr; can also pass either pointers or structures in and out of functions. arrays: struct planet balls[8]; balls[0].order = 1; balls[0].distance = 60e6; strcpy(balls[0].name, "mercury"); arrays of pointers struct planet *pballs[1000]; pballs[2] = &earth; pballs[7] = (struct planet *) malloc (sizeof(struct planet)); if (!pballs[7]) { perror("malloc failure"); exit(EXIT_FAILURE); } list of planets: struct pnode { struct pnode* next; struct planet data; } struct pnode * nptr = (struct pnode*) malloc(sizeof(struct pnode)); if (!nptr) { perror("malloc failure"); exit(EXIT_FAILURE); } Unions A union is used to hold different things at different times. It can hold only one thing at a time. The program needs to keep track of the right attitude / nature of the contents. The variable is large enough to hold the largest of the possibilities. The syntax is the same as for structs. Often a struct is used to wrap a union and disambiguate the contents. enum u_e {INT, DOUBLE, STR, CHAR} u_e; typedef union u_t {int i; double d; char *str; char ch} u_t; typedef struct s_t {u_e type; u_t data} s_t; Typedef: preferred typedef struct planet planet_t; typedef struct node { struct node *next; planet_t data; } node_t; Malloc/free remember not to leak memory. remember realloc and calloc Alignment mallocsize.c Use of MALLOC_CHECK (environment) Use of _FORTIFY_SOURCE BitFields if there's time (there wasn't when I did this in winter 2009) unsigned int a :3; signed int b: 5; they are not arrays. They do not have addresses. They are ints only. They are implementation-dependent in almost every way. LAB: Write a program that reads characters into a list, inserting at the head, then uses the list to print the string backwards. Define the list elements as structs. vim: set sts=2 sw=2 ai et : ...
View Full Document

Ask a homework question - tutors are online