Presentation is loading. Please wait.

Presentation is loading. Please wait.

User-defined data types

Similar presentations


Presentation on theme: "User-defined data types"— Presentation transcript:

1 User-defined data types
Structures A collection of other data types Used a lot for organized complex data structures Can be used for Object-Orient Programming in C Unions A combination of various different types

2 Basic Structures -- Declaration
struct [tag] {members} [variables] ; Type declaration with tag: struct point { int x; int y; }; Used later for variable declaration: struct point a, b; Also valid: int y; } a, b; struct { int x; int y; } a, b;

3 Structure Usage Member access Hierarchical struct sname.member;
a.x and a.y; Hierarchical struct struct members can be of any type, including a struct nested structs struct rect { struct point low_left; struct point top_right; } box; box.low_left.x;

4 Structure Arithmetic member access initiation, copy/assignment
a.x = 2; a.y = 1; initiation, copy/assignment struct point b = {1, 2}; b = a; b = {1,2}; /* Wrong */ Need to be of the same type

5 Structure and Functions
Use function to initialize structure variables make_point(1, 2); More structure functions make_rect (a, b); distance (a, b); All variables are passed by value, can be inefficient for large structures structure functions w/ pointers distance (&a, &b); Member access with structure pointers sname_pt->member (*sname_pt).member

6 Structure Arrays A new declaration of rectangle
struct point {int x, int y} pt[2]; Students in class c459.21 struct student { char name[10]; int score; }; struct student c459[10];

7 Structure Arrays -- Continued
Calculate average score int average(struct student c1[], int n) { int i, total =0; for (i = 0; i < n ; i++) { total += c1[i].score; } return (total/(double)n); int main() { struct student c459[] = { “John”, 90, “Adam”, 80, }; average(c459, sizeof(c459)/sizeof(struct student)); return 0; }

8 Structure Pointers Calculate average score int main()
int average(struct student *p, int n) { int i, total =0; for (i = 0; i < n ; p++, i++) { total += p->score; } return (total/(double)n); int main() { struct student c459[] = { “John”, 90, “Adam”, 80, }; average(c459, sizeof(c459)/sizeof(struct student)); return 0; }

9 Unions A combination of various different types
Syntax like structures, but different implications The size of a union is the maxim of all The size of a struct is at least the combination of all Same memory content with different representation union num_rep { int x; short s; char c; }; union addr { char *cp; int *ip; int value; };

10 More on user defined data types
sizeof Safe way to tell the size of structures or unions struct s2 { int x; char c; short s; }; typedef Specify a new name for the same type


Download ppt "User-defined data types"

Similar presentations


Ads by Google