Programming in C Arrays Structs and Strings 72809

  • Slides: 26
Download presentation
Programming in C Arrays, Structs and Strings 7/28/09

Programming in C Arrays, Structs and Strings 7/28/09

Arrays • An array is a collection of individual data elements that is: –

Arrays • An array is a collection of individual data elements that is: – Ordered -- we can count off the elements 0, 1, 2, 3, . . . – Fixed in size – Homogeneous -- all of the elements have to be of the same type, e. g. , int, float, char, etc. • In C, each array has two fundamental properties: – the element type – the size 7/28/09 2

Array Example The following code declares an array of 100 integers and initializes the

Array Example The following code declares an array of 100 integers and initializes the first and last element. Note that C arrays are always indexed from 0 (zero) int scores[100]; scores[0] = 17; scores[99] = 42; 7/28/09 3

Array Initialization • Arrays may be initialized when declared int grades[ 10 ] =

Array Initialization • Arrays may be initialized when declared int grades[ 10 ] = { 90, 80, 70 }; double temps [5] = { 23. 7, 12. 3, 45. 6, 5. 55, 67. 8 }; • Or you can let the compiler calculate it’s length int scores[ ] = { 99, 42, 33, 55, 66, 78 }; 7/28/09 4

Arrays in Memory • The name of the array refers to the whole array

Arrays in Memory • The name of the array refers to the whole array by acting like a pointer (the memory address) of the start of the array scores . . . 0 1 98 99 Someone else’s memory 7/28/09 Don’t read/write here 5

2 -d Arrays • The following code declares a 2 -d array of ints

2 -d Arrays • The following code declares a 2 -d array of ints and initializes the first and last elements int board[10][12]; board[0][0] = 13; board[9][11] = 42; • Although conceptually a table with rows and columns, 2 -d arrays are implemented as a single contiguous block of memory with elements of the rightmost index next to each other. E. g. board[1][8] comes right before board[1][9] 7/28/09 6

More typedefs • typedefs can be used to simplify complex declarations such as arrays

More typedefs • typedefs can be used to simplify complex declarations such as arrays and 2 -d array – The declaration typedef int ROW[4]; defines ROW as a new name for an array of 4 integers that now be as a data type ROW row 1, row 2; void print. Row( ROW r ); – The declaration typedef int TABLE[2][3]; defines TABLE as a new name for a 2 -d array of integers TABLE scores; void print. Table( TABLE t); 1/14/10 7

Arrays and Functions • • • C passes arguments to functions “by value” A

Arrays and Functions • • • C passes arguments to functions “by value” A copy of the argument is used in the function When passing an array by name, a copy of the array’s starting address is passed to the function, not a copy of the array itself • As a result, references to array elements within the function are also references to the array argument. 7/28/09 8

Array Argument Example void add. Two( int a[], int size ) { int k;

Array Argument Example void add. Two( int a[], int size ) { int k; for (k = 0; k < size; k++) a[k] += 2; } int main( ) { int j, scores[3]; scores[0] = 42; scores[1] = 33; scores[2] = 99; add. Two( scores, 3); for (j = 0; j < 3; j++) printf(“%d “, scores[j]); /* 44, 35, 101 */ return 0; } 7/28/09 9

No Classes in C • Because C is not an OOP language, there is

No Classes in C • Because C is not an OOP language, there is no way to combine data and code into a single entity. C does allow us to combine related data into a structure using the keyword struct. All data in a struct can be accessed by any code. The general form of a structure definition is struct tag { member 1_declaration; member 2_declaration; member 3_declaration; . . . Note the semi-colon member. N_declaration; }; where struct is the keyword, tag names this kind of struct, and member_declarations are variable declarations which define the members. 7/28/09 10

C struct Example • Defining a struct to represent a point in a coordinate

C struct Example • Defining a struct to represent a point in a coordinate plane struct point { int x; /* x-coordinate */ int y; /* y-coordinate */ }; is the struct tag • Given the declarations struct point p 1; struct point p 2; we can access the members of these struct variables: * the x-coordinate of p 1 is p 1. x * the y-coordinate of p 1 is p 1. y * the x-coordinate of p 2 is p 2. x * the y-coordinate of p 2 is p 2. y 7/28/09 11

Using structs and members • Like other variable types, struct variables (e. g. p

Using structs and members • Like other variable types, struct variables (e. g. p 1, p 2) can be passed to functions as parameters and returned from functions as return types. • The members of a struct are variables just like any other and ca be used wherever any other variable of the same type may be used. For example, the members of the struct point can then be used just like any other integer variables. 7/28/09 12

print. Point. c struct point input. Point( ) { struct point p; printf(“please input

print. Point. c struct point input. Point( ) { struct point p; printf(“please input the points x- and y-coordinates: “); scanf(“%d %d”, &p. x, &p. y); return p; } void print. Point( struct point ) { printf (“( %2 d, %2 d )”, point. x, point. y); } int main ( ) { struct point endpoint; endpoint = input. Point( ); print. Point( endpoint ); return 0; } 7/28/09 13

struct assignment • The contents of a struct variable may be copied to another

struct assignment • The contents of a struct variable may be copied to another struct variable of the same type using the assignment (=) operator • After this code is executed struct p 1. x = p 1. y = point p 1; point p 2; 42; 59; p 2 = p 1; /* structure assignment copies members */ The values of p 2’s members are the same as p 1’s members. E. g. p 1. x = p 2. x = 42 and p 1. y = p 2. y = 59 7/28/09 14

struct within a struct • A data element in a struct may be another

struct within a struct • A data element in a struct may be another struct (similar to composition in Java / C++). • This example defines a line in the coordinate plane by specifying its endpoints as POINT structs struct line { struct point left. End. Point; struct point right. End. Point; }; • Given the declarations below, how do we access the x- and y-coodinates of each line’s endpoints? struct line 1, line 2; 7/28/09 15

Arrays of struct • Since a struct is a variable type, we can create

Arrays of struct • Since a struct is a variable type, we can create arrays of structs just like we create arrays of int, char, double, etc. • Write the declaration for an array of 5 line structures name “lines” struct lines[ 5 ]; 1/20/10 16

Array of struct Code /* assume same point and line struct definitions */ int

Array of struct Code /* assume same point and line struct definitions */ int main( ) { struct lines[5]; int k; /* write code to initialize all data members to zero */ for (k = 0; k < 5; k++) { lines[k]. left. End. Point. x = 0; lines[k]. left. End. Point. y = 0; lines[k]. right. End. Point. x = 0; lines[k]. right. End. Point. y = 0; } /* call the print. Point( ) function to print ** the left end point of the 3 rd line */ print. Point( lines[2]. lef. End. Point); return 0; } 1/20/10 17

Bitfields • When saving space in memory or a communications message is of paramount

Bitfields • When saving space in memory or a communications message is of paramount importance, we sometimes need to pack lots of information into a small space. We can use struct syntax to define “variables” which are as small as 1 bit in size. These variables are known as “bit fields”. struct weather { unsigned unsigned int int int temperature : 5; wind. Speed : 6; is. Raining : 1; is. Sunny : 1; is. Snowing : 1; }; 7/28/09 18

Using Bitfields struct weather todays. Weather; todays. Weather. temperature = 44; todays. Weather. is.

Using Bitfields struct weather todays. Weather; todays. Weather. temperature = 44; todays. Weather. is. Snowing = 0; todays. Weather. wind. Speed = 23; /* etc */ if (todays. Weather. is. Raining) printf( “%sn”, “Take your umbrella”); if (todays. Weather. temperature < 32 ) printf( “%sn”, “Stay home”); 7/28/09 19

More on Bit fields • Almost everything about bit fields is machine and compiler

More on Bit fields • Almost everything about bit fields is machine and compiler specific. • Bit fields may only defined as (unsigned) ints • Bit fields do not have memory addresses, so the & operator cannot be applied to them • We’ll see more on this later 7/28/09 20

Unions • A union is a variable type that may hold different type of

Unions • A union is a variable type that may hold different type of members of different sizes, BUT only one type at a time. All members of the union share the same memory. The compiler assigns enough memory for the largest of the member types. • The syntax for defining a union and using its members is the same as the syntax for a struct. 7/28/09 21

Formal Union Definition • The general form of a union definition is union tag

Formal Union Definition • The general form of a union definition is union tag { member 1_declaration; member 2_declaration; member 3_declaration; . . . member. N_declaration; }; where union is the keyword, tag names this kind of union, and member_declarations are variable declarations which define the members. Note that the syntax for defining a union is exactly the same as the syntax for a struct. 7/28/09 22

union. c union data { int x; char c[4]; } ; int i; union

union. c union data { int x; char c[4]; } ; int i; union data item; item. x = 42; printf(“%d, %o, %x”, item. x, item. x ); for (i = 0; i < 4; i++ ) printf(“%x ”, item. c[i]); printf( “%s”, “n”); printf(“%sn”, “size of data = ”, sizeof(data)); 1/20/10 23

Union vs. Struct • Similarities – Definition syntax virtually identical – Member access syntax

Union vs. Struct • Similarities – Definition syntax virtually identical – Member access syntax identical • Differences – Members of a struct each have their own address in memory. – The size of a struct is at least as big as the sum of the sizes of the members (more on this later) – Members of a union share the same memory. The size of a union is the size of the largest member. 7/28/09 24

Using typedef with a struct • typedef is often used for structs to make

Using typedef with a struct • typedef is often used for structs to make coding easier for lazy programmers who can’t type well. In this case the struct tag (point) is not required. typedef int COORDINATE; typedef struct point { COORDINATE x; /* x-coordinate */ COORDINATE y; /* y-coordinate */ } POINT; /* POINT is an alias for this struct */ /* use the alias to declare variables */ POINT p 1, p 2, endpoint, origin; 7/28/09 25

End of Class 3 7/28/09 26

End of Class 3 7/28/09 26