Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.

Similar presentations


Presentation on theme: "Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of."— Presentation transcript:

1 Programming in C Arrays, Structs and Strings

2 7/28/092 Arrays An array is a collection of individual data elements that is: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:In C, each array has two fundamental properties: –the element type –the size

3 7/28/093 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;

4 7/28/094 Array Initialization Arrays may be initialized when declaredArrays 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 lengthOr you can let the compiler calculate it’s length int scores[ ] = { 99, 42, 33, 55, 66, 78 };

5 7/28/095 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 arrayThe name of the array refers to the whole array by acting like a pointer (the memory address) of the start of the array 01 9899...... scores Someone else’s memory Don’t read/write here

6 7/28/096 2-d Arrays The following code declares a 2-d array of ints and initializes the first and last elementsThe 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]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 1/14/107 More typedefs typedefs can be used to simplify complex declarations such as arrays and 2-d arraytypedefs 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 row1, row2; void printRow( 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 printTable( TABLE t);

8 7/28/098 Arrays and Functions C passes arguments to functions “by value”C passes arguments to functions “by value” A copy of the argument is used in the functionA 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 itselfWhen 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.As a result, references to array elements within the function are also references to the array argument.

9 7/28/099 Array Argument Example void addTwo( 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; addTwo( scores, 3); for (j = 0; j < 3; j++) printf(“%d “, scores[j]); /* 44, 35, 101 */ return 0; }

10 7/28/0910 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 isBecause 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 { member1_declaration; member1_declaration; member2_declaration; member2_declaration; member3_declaration; member3_declaration;...... memberN_declaration; memberN_declaration; }; }; where struct is the keyword, tag names this kind of struct, and member_declarations are variable declarations which define the members. where struct is the keyword, tag names this kind of struct, and member_declarations are variable declarations which define the members. Note the semi-colon

11 7/28/0911 C struct Example Defining a struct to represent a point in a coordinate planeDefining a struct to represent a point in a coordinate plane struct point { int x;/* x-coordinate */ int y;/* y-coordinate */ }; Given the declarationsGiven the declarations struct point p1; struct point p2; we can access the members of these struct variables: * the x-coordinate of p1 is p1.x * the y-coordinate of p1 is p1.y * the x-coordinate of p2 is p2.x * the y-coordinate of p2 is p2.y point is the struct tag

12 7/28/0912 Using structs and members Like other variable types, struct variables (e.g. p1, p2) can be passed to functions as parameters and returned from functions as return types.Like other variable types, struct variables (e.g. p1, p2) 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 can then be used just like any other integer variables.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.

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

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

15 7/28/0915 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 struct s struct line { struct point leftEndPoint; struct point rightEndPoint; }; Given the declarations below, how do we access the x- and y-coodinates of each line’s endpoints? struct line line1, line2;

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

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

18 7/28/0918 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 syntax to define “variables” which are as small as 1 bit in size. These variables are known as “bit fields”.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 int temperature : 5; unsigned int windSpeed : 6; unsigned int isRaining : 1; unsigned int isSunny : 1; unsigned int isSnowing : 1; };

19 7/28/0919 Using Bitfields struct weather todaysWeather; todaysWeather.temperature = 44; todaysWeather.isSnowing = 0; todaysWeather.windSpeed = 23; /* etc */ if (todaysWeather.isRaining) printf( “%s\n”, “Take your umbrella”); if (todaysWeather.temperature < 32 ) printf( “%s\n”, “Stay home”);

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

21 7/28/0921 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.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.The syntax for defining a union and using its members is the same as the syntax for a struct.

22 7/28/0922 Formal Union Definition The general form of a union definition isThe general form of a union definition is union tag { member1_declaration; member1_declaration; member2_declaration; member2_declaration; member3_declaration; member3_declaration;...... memberN_declaration; memberN_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. 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.

23 1/20/1023 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, item.x ); for (i = 0; i < 4; i++ ) printf(“%x ”, item.c[i]); printf( “%s”, “\n”); printf(“%s\n”, “size of data = ”, sizeof(data));

24 7/28/0924 Union vs. Struct SimilaritiesSimilarities –Definition syntax virtually identical –Member access syntax identical DifferencesDifferences –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.

25 7/28/0925 Using typedef with a struct typedef is often used for struct s to make coding easier for lazy programmers who can’t type well. In this case the struct tag ( point ) is not required.typedef is often used for struct s 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 p1, p2, endpoint, origin;

26 7/28/0926 End of Class 3


Download ppt "Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of."

Similar presentations


Ads by Google