Download presentation
Presentation is loading. Please wait.
Published byRandolf Morgan Modified over 6 years ago
1
CS1001 Programing Fundamental Lecture 12 Strings and Structured Type
(Chapter 9, 11) Lecturer: Narong Wesnarat
2
Strings Basics Strings are Arrays of Characters Example:
char s [10]; declares a 10-element array that can hold a character string of up to 9 characters, the last one is the null character ‘\0’ Convention: Use the null character ’\0’ to terminate all strings Declaring and Initializing String Variables char university[12] = “Shinawatra” ; char city[] = “Bangkok” This is called string constant or string literal . No need to specify the size of the string. [0] [6] [7] [8] [9] [2] [3] [4] [5] [1] h S n i w a t r ? \0 [10] [11] terminates with null unknown [0] [6] [7] [2] [3] [4] [5] [1] a B g n o k \0
3
Strings Basics Strings can not be assigned or compared the same way as int, char or double types Examples: char university[12] = “Shinawatra” ; char city[] = “Bangkok” university = “Bangkok”; //Wrong ! if(university == city) printf(“Equal!\n”); //Wrong! Use string functions instead: strcpy(university, city); //replace Shinawatra by Bangkok if(strcmp(city,university)==0) printf(“Equal!\n”);
4
Arrays of Strings Because a string is an array of characters, an array of strings is a two-dimensinal array of characters in which each row is one string. Example: char seasons[4] [7] = {“winter”, “spring”, “summer”, “fall”}; Distinction between characters and strings [0] [6] [2] [3] [4] [5] [1] i w t n r e \0 p s g u m a f l ? /* to print the seasons out */ for(i = 0 ; i < 4 ; i++) printf(“ %s \n”, seasons[ i ] ); G \0 Character ‘G’ (one byte) String “G” (two bytes) "" empty string
5
Accessing Individual Characters
Use indexing, just as for any other kind of array: char s[10]; s[0] = 'h'; s[1] = 'i’; s[2] = '!'; s[3] = '\0'; Use single quotes with char literals, and double quotes with string literals char str[]=“HELLO”; printf(“%c”,str[1]); or printf(“%c”,”HELLO”[1]); only ‘E’ will be printed ! E H L O \0 [0] [5] [2] [3] [4] [1]
6
Different ways of accessing strings
#include<stdio.h> #include<string.h> int main (void) {int i,j; char seasons[4] [7] = {"winter", "spring", "summer", "fall"}; printf( "%c\n", "HELLO"[0]); printf( "%c\n", "HELLO"[1]); printf( "%c\n", "HELLO"[2]); /* to print the seasons out using seasons[0] ... seasons[3]*/ for(i = 0 ; i < 4 ; i++) printf("=%s \n", seasons[ i ] ); /* or another way by using pointer to seasons would be */ for(j = 0; j < 4; j++) printf("-%s\n", *(seasons + j)); /* still another way would be */ { for(i = 0; i < 7; i++) printf("=%c", *(*(seasons+j) + i)); printf("\n"); } printf("-%c",seasons[j][i]); return 0;
7
Output Strings with printf
Printing Strings with printf ( ) char str[ ] = "A message to display"; printf ("%s\n", str); this will print A message to display with newline character. printf expects to receive a string parameter when it sees %s in the format string Alignment with Placeholders Value Placeholder Output(# means blank) “fantastic” %s fantastic %6s fantastic string longer, print all %12s ###fantastic align right %-12s fantastic### align left %5.3s ##fan reserve 5, print 3 char Format place holder for string
8
Printing with puts( ) Prints out:
The puts function is much simpler than printf for printing strings Prototype of puts is defined in stdio.h: int puts(const char * str); More efficient than printf: the program doesn't need to analyze the format string at run-time Example: char sentence[ ] = "The quick brown fox\n"; puts(sentence); Prints out: The quick brown fox puts adds a newline ‘\n’ character following the string
9
Inputting Strings with scanf( )
/* Assume s1, s2 and s3 are char arrays */ scanf ("%s", s1); scanf ("%5s%[a-f1-0pxw]%[^e] ", s1, s2, s3); To read a string include: %s scans up to but not including the next white space character %ns scans the next n characters or up to the next white space character(space or newline) , whichever comes first To read strings not delimited by space characters, a set of characters in brackets ([ ]) can be substituted for the s (string) type character. The corresponding input field is read up to the first character that does not appear in the bracketed character set. If the first character in the set is a caret (^), the effect is reversed: The input field is read up to the first character that does appear in the rest of the character set. Note that %[a-z] and %[z-a] are interpreted as equivalent to %[abcde...z]. The process stops when a white space character or EOF is encountered. At that point a null character is placed in memory to end the string. Note: No address operator (&) is used with the actual parameter when inputting strings into character arrays: the array name is an address already
10
Inputting a String using scanf
After declaration: char str[20],s1[22],s2[22],s3[33]; while(1) { printf("Enter a string s:"); scanf( "%s",str); printf("1. %s\n",str); fflush(stdin); /*Clear Keyboard buffer*/ printf("Enter a string [a b-dx35]:"); scanf("%[a b-dx35]",str); printf("2. %s\n",str); fflush(stdin); printf("Enter a string [^e]:"); scanf("%[^e]",str); printf("3. %s\n",str); printf("Enter a string 5s 3s 7s:"); scanf("%5s%3s%7s", s1, s2, s3); printf("4. %s %s %s\n",s1,s2,s3); } space included
11
Inputting Strings with gets( )
gets( ) gets a line from standard input The prototype is defined in stdio.h: char *gets(char *str); str is a pointer to the space where gets will store the line, or a character array Returns NULL (the null pointer) upon failure. Otherwise, it returns str Note the additional meaning for operator *
12
Inputting Strings with gets( )
Example: char your_line[100]; printf("Enter a line:\n"); gets(your_line); puts("Your input follows:\n"); puts(your_line); Newline character is not stored, but the null character is Make sure the array is big enough to hold the line being read; otherwise, input will overflow into other areas of memory
13
The C String Library String functions are provided in an ANSI standard string library Access this through its header file: #include <string.h> Includes functions to perform tasks such as: Computing length of string Copying strings Concatenating strings This library is guaranteed to be there in any ANSI standard implementation of C
14
Functions from string.h
strlen returns the length of a NULL terminated character string: size_t strlen (char * str) ; size_t: a type defined in string.h that is equivalent to an unsigned int char *str: points to a series of characters or is a character array ending with '\0' What’s wrong with: char a[5]={‘a’, ’b’, ’c’, ’d’, ’e’}; n = strlen(a); no space to store ‘\0’ , unknown length
15
Functions from string.h
strcpy makes a copy of a string: char *strcpy (char * destination, char * source); A copy of the string at address source is made at destination String at source should be null-terminated destination should point to enough room (at least enough to hold the string at source) The return value is the address of the copied string (that is, destination)
16
Functions from string.h
strcat concatenates strings: char * strcat (char * str1, char * str2); Appends a copy of str2 to the end of str1 The result string is null-terminated str2 is not modified A pointer equal to str1 is returned Programmer must ensure that str1 has sufficient space to hold the concatenated string
17
Example #include <string.h> #include <stdio.h>
puts adds a newline #include <string.h> #include <stdio.h> int main() { char str1[27] = "abc"; char str2[100]; printf("str1 length = %d\n",strlen(str1)); strcpy(str2,str1); printf("str2=:"); puts(str2); puts("newline\n"); strcat(str2,str1); }
18
Functions from string.h
strcmp compares strings for equality or inequality: int strcmp (char *str1, char *str2); Returns an int whose value is interpreted as follows: < 0 : str1 is less than str2 0 : str1 is equal to str2 > 0 : str1 is greater than str2
19
Functions from string.h
strcmp compares the strings one char at a time until a difference is found; return value is (the ASCII ordinal value of the char from str1) minus (the ASCII ordinal value of the char from str2) If both strings reach a '\0' at the same time, they are considered equal, and return value is zero
20
Functions from string.h
Other string comparison functions: int strncmp (char *str1, char * str2, size_t n); Compares at most n chars of str1 and str2 Continues until a difference is found in the first n chars, or n chars have been compared without detecting a difference, or the end of str1 or str2 is encountered strcasecmp( ) and strncasecmp( ): same as strcmp( ) and strncmp( ), except that differences between upper and lower case letters are ignored
21
Function strncmp example
#include <string.h> int main() { char str1[ ] = "The first string."; char str2[ ] = "The second string."; size_t n, x; printf("%d\n", strncmp(str1, str2, 4) ); // print 0 printf("%d\n", strncmp(str1, str2, 7) ); // print -1 }
22
Functions strchr strchr: Find the first occurrence of a specified character in a string: char * strchr (char * str, int ch) ; Search the string referenced by str from its beginning, until either an occurrence of ch is found or the end of the string (‘\0’) is reached Return a pointer to the first occurrence of ch in the string; if no occurrence is found, return the NULL pointer instead
23
Function strchr Value returned by strchr can be used to determine the position (index) of the character in the string: Subtract the start address of the string from the value returned by strchr This is pointer arithmetic: the result is offset of the character, in terms of char locations, from the beginning of the string Will work even if sizeof(char) is not 1
24
Functions from string.h Example
#include<stdio.h> #include<string.h> int main( ) { char ch='b', buf[80]; strcpy(buf, "The quick brown fox"); if (strchr(buf,ch) == NULL) printf ("The character %c was not found.\n",ch); else printf ("The character %c was found at position %d\n", ch, strchr(buf,ch)-buf+1); } Output: The character b was found at position 11 ‘b’ is the 11th character in buf; in fact, it is stored in buf[10]
25
Function strstr strstr searches for the first occurrence of one string inside another: char * strstr (char * str, char * query) ; If found, a pointer to the first occurrence of query inside str is returned; otherwise the NULL pointer is returned
26
Functions from stdlib.h
atoi : takes a character string and converts it to an integer int atoi (char *ptr); Ignores leading white space in the string Then expects either + or – or a digit No white space allowed between the sign and the first digit Converts digit by digit until a non-digit (or the end of the string) is encountered
27
Functions from stdlib.h
Examples using atoi : string s atoi( s ) “394” 394 “ ” 157 “-1.6” -1 “ x” 50 “twelve” 0 “x506” 0 “ ” 0
28
Functions from stdlib.h
long atol (char *ptr) ;/* like atoi, but returns a long */ double atof (char * str); Like atoi, but for real values Handles a decimal point, and an exponent indicator (e or E) followed by an integer exponent string s atof( s ) “12-6” “ ” “123E+3” “123.1e-5.64”
29
String functions Demo #include <string.h>
#include <stdio.h> #include <string.h> #include<stdlib.h> int main() { /* Demonstration of string functions Author: Narong Wesnarat */ int i,j,k,n,m; unsigned *add1,*add2; char str1[150],str2[150],str3[150],str4[10][30]; char ch='b', buf[80]; strcpy(str1," ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); strcpy(buf,"The quick brown fox jumps over the lazy dog."); strcpy(str2,buf); strcpy(str3,str1); printf("str1 = %s\n",str1); printf("str2 = %s\n",str2); printf("str3 = %s\n",str3); printf("buf = %s\n",buf); printf("strcpy(buf,str1)\n"); strcpy(buf,str1); printf("strncpy(buf,str2,9)\n"); strncpy(buf,str2,9); k=strcmp(str1,str2); i=strcmp(str1,str3); String functions Demo
30
String functions Demo printf("\nstrcmp(str1,str2)= %d\n",k);
printf("strcmp(str1,str3)= %d\n",i); printf("strcmp(str2,str3)= %d\n",strcmp(str2,str3)); printf("strcmp(buf,str2)= %d\n",strcmp(buf,str2)); printf("strncmp(buf,str2,9)= %d\n",strncmp(buf,str2,9)); printf("\nbuf = %s\n",buf); printf("Address of buf = %u\n",&buf); if (strchr(buf,ch) == NULL) printf ("The character %c was not found.\n",ch); else printf ("The character %c was found in buf at position %ld\n", ch, strchr(buf,ch)-buf+1); if (strstr(buf,"GHIJK") == NULL) printf ("The string \"GHIJK\" was not found in buf.\n"); { add1=strstr(buf,"GHIJK"); printf ("The string \"GHIJK\" was found in buf at address %u,\n",add1); printf("or at position = %u \- %u \+ 1 = %ld.\n",add1,buf,strstr(buf,"GHIJK")-buf+1); } if (strstr(buf,"GOD") == NULL) printf ("The string \"GOD\" was not found in buf.\n"); printf ("The string \"GOD\" was found in buf at position %ld\n", strstr(buf,"GOD")-buf+1);
31
String functions Demo
32
Using arrays of strings
Arrays of strings can be used to store string data. Example: This program uses parallel arrays of strings to store names and surnames. Sorting of parallel arrays of string. Note: swapping must be for all parallel array elements. int sort(char srtname[][20],double srtgpa[],int n) {int i,j; char ctmp[20]; double dtmp; for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) if(strcmp(srtname[i], srtgpa[j])>0) //swap name strcpy(ctmp,nm[i]); strcpy(nm[i],nm[j]); strcpy(nm[j],ctmp); //swap gpa dtmp = srtgpa[i]; srtgpa[i] = srtgpa[j]; srtgpa[j] = dtmp; } return(0); #include<stdio.h> #include<string.h> void display(char dpname[][20], double dpgpa[], int n); int sort(char srtname[][20],char srtgpa[], int n); int main() { int i,j,k,n,choice; long id[100]; char name[100][30]; double gpa[100]; for(i=0;i<100;i++) printf("Enter Name,Surname(999 to stop): "); scanf("%20s%lf", name[i], gpa[i]); if (strcmp(name[i],"999") == 0) break; }
33
Sorting parallel arrays of strings full listing.
void display(char nm[][20],char snm[][20],int n) {int i; printf("\nName Surname\n\n"); for(i=0;i<n;i++) printf("%s\t\t%s\n",nm[i],snm[i]); printf("End of list\n"); return; } int sort(char nm[][20],char snm[][20],int n) {int i,j; char ctmp[20],ct; for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) if(strcmp(nm[i],nm[j])>0) //swap nm strcpy(ctmp,nm[i]); strcpy(nm[i],nm[j]); strcpy(nm[j],ctmp); //swap snm strcpy(ctmp,snm[i]); strcpy(snm[i],snm[j]); strcpy(snm[j],ctmp); return(0); #include<stdio.h> #include<string.h> void display(char nm[][20],char snm[],int n); int sort(char nm[][20],char snm[][20],int n); int main() { int i,j,k,n,choice; long id[100]; char name[100][20],sname[100][20]; /* scan name and surname into the arrays until name = 999 */ for(i=0;i<100;i++) printf("Enter Name, Surname(999 to stop): "); scanf("%20s%20s", name[i], sname[i]); if(strcmp(name[i],"999")==0) break; } j=i; display(name,sname,j); sort(name,sname,j); return; } /* End of Main */
34
Structure and Union Types
A structure is a data type that can have individual components that contain data of different types. Data items can be stored in a separate component of the structure and can be referenced by using the component name. Defining a Structure Type We can define a structure to accommodate the book as follows: typedef struct { char Name[100]; char Author[100]; char Publisher[80]; int Year; double Price; } Book; The keyword struct defines a book, and each line with in the braces defines the elements of the Book. Now when ever we create an instance of Book it will have all the elements of the structure i.e. Name, Author, Publisher and Year.
35
Declaring a Structure variable
A structure variable can be declared by specifying the defined structure type follow by a structure variable name, as for the structure type Book: Book CProgrammingBook; Declaring & Initializing a Structure Variable We can initialize the structure variable similar to a string but with the declared type, e.g., for the CProgrammingBook named “Beginning VC++6”, that authored by Ivor Horton, publisher is Wrox and published in the year 2001, Price $16.5, Book CProgrammingBook = { "Beginning VC++ 6", "Ivor Horton", "Wrox", 2001 , 16.5 };
36
Accessing the members of a Structure Variable
We can access a member of a structure variable by adding a period after the name of the structure variable name and then the name of the field we want to access. For example we want to change the Publish year from 2001 to 2002, and Publisher to McGraw-Hill, we will do it as CProgrammingBook.Year = 2002; //for integer member strcpy(CProgrammingBook.Publisher=“McGraw=Hill”); //for string member
37
Using Structure Type, an example
print_Book(CProgrammingBook); printf("===Changed===\n"); CProgrammingBook.Year = 2002; strcpy(CProgrammingBook.Publisher,"McGraw-Hill"); return(0); }/*End of Main*/ void print_Book(Book AnyBook) { printf("Book Title\t\t: %s\n",AnyBook.Name); printf("Book Author\t\t: %s\n",AnyBook.Author); printf("Book Publisher\t\t: %s\n",AnyBook.Publisher); printf("Book Plubished Year\t: %d\n",AnyBook.Year); printf("Book Price\t\t: %-6.2f\n",AnyBook.Price); //align left the price } #include<stdio.h> #include<string.h> typedef struct /* Defining the structure type Book */ { char Name[100]; char Author[100]; char Publisher[80]; int Year; double Price; }Book; void print_Book(Book AnyBook); int main() /* Declaring and initializing a structure variable name CProgrammingBook*/ Book CProgrammingBook = "Beginning VC++ 6", "Ivor Horton", "Wrox", 2001, 16.5 };
38
Structure Type Definition
This is a struct type planet_t declaration designed to store characteristics of a planet, for example Jupiter: Name: Jupiter Diameter: ,800 km Moons: Orbit time: yr Rotation time: hr typedef allocate no memory. It is needed to declare a struct variable to allocate storage space for a structured data object. planet_t current_planet, privious_planet, blank_planet = {“”, 0, 0, 0,0}; current_planet, previous_planet and blank_planet are variables of type planet_t. SYNTAX in general: typedef struct{ type1 id_list; type2 id_list; . type n id_list; } struct_type; Example: typedef struct { char name[10]; double diameter; int moons; double orbit_time, rotation_time; } planet_t;
39
Figure 11.1 Assigning Values to Components of Variable current_planet
40
Manipulating Individual Components of a Structured Data Object
A component of a structure can be referenced by using the direct component selection operator, which is a period ‘.’. Examples: strcpy( current_planet.name,”Jupiter”); printf(“%s’s equatorial diameter is %.1fkm.\n”, current_planet.name, current_planet.diameter); this displays Jupiter’s equatorial diameter is km. Manipulating Whole Structure The name of a structure type variable used with no component election operator refers to the entire structure. previous_planet = current_planet;
41
Structure Type Data as Input Parameters
Structured input parameter is declared by structure type name follows by a stucture variable This function print components of planet_t pl as they are sent from the main All values of planet_t pl in the main are not changed Figure Function with a Structured Input Parameter /* Displays with labels all components of a planet_t structure */ void print_planet ( planet_t pl ) /* input - one planet structure */ { printf("%s\n", pl.name); printf(" Equatorial diameter: %.0f km\n", pl.diameter); printf(" Number of moons: %d\n", pl.moons); printf(" Time to complete one orbit of the sun: %.2f years\n", pl.orbit_time); printf(" Time to complete one rotation on axis: %.4f hours\n", pl.rotation_time); }
42
Function Comparing Two Structured Values for Equality
Figure Function Comparing Two Structured Values for Equality #include <string.h> /* * Determines whether or not the components of planet_1 and planet_2 match */ int planet_equal (planet_t planet_1, /* input - planets to */ planet_t planet_2) /* compare */ { return (strcmp(planet_1.name, planet_2.name) == 0 && planet_1.diameter == planet_2.diameter && planet_1.moons == planet_2.moons && planet_1.orbit_time == planet_2.orbit_time && planet_1.rotation_time == planet_2.rotation_time ); }
43
Function with a Structured Output Argument
An output argument is declared in a function using a pointer to a structure variable /* Figure Function with a Structured Output Argument * Fills a type planet_t structure with input data. Integer returned as * function result is success/failure/EOF indicator. * => successful input of one planet * => error encountered * EOF => insufficient data before end of file * In case of error or EOF, value of type planet_t output argument is * undefined. */ int scan_planet (planet_t *plnp) /* output - address of planet_t structure to fill */ { int result; result = scanf("%s%lf%d%lf%lf",(*plnp).name, &(*plnp).diameter, &(*plnp).moons, &(*plnp).orbit_time, &(*plnp).rotation_time); if (result == 5) result = 1; /* successfully scan all 5 members */ else if (result != EOF) result = 0; /* inficient data */ return (result); } Reference Type Value plnp planet_t * address of structure that main refers to as current_planet *plnp planet_t structure that main refers to as current_planet (*plnp).diameter double &(*plnp).diameter double * address of colored component of structure that main refers to as current_planet scanf returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end-of-file character or the end-of-string character is encountered in the first attempt to read a character.
44
Functions Whose Result Values Are Structured
A local variable of the structure type can be allocated, filled with desired data, and returned as a function result. The function does not return the address of the structure as it would with an array result; rather it returns the values of all components. Figure Function get_planet Returning a Structured Result Type planet_t get_planet(void) { planet_t planet; scanf("%s%lf%d%lf%lf", planet.name, &planet.diameter, &planet.moons, &planet.orbit_time, &planet.rotation_time); return (planet); } the statment current_planet = get_planet(); has the same effect as scan_planet(¤t_planet);
45
Parallel Arrays and Arrays of Structures
A data collection may contains items of different types or items that, although of the same type but represent quite distinct concept. Two methods can be used to store them. Parallel Arrays int id[50]; double gpa[50]; double x[10],y[10]; Array of Structures #define MAX_STU 50 #define NUM_PTS 10 typedef struct { int id; double gpa; }student_t; /*declare structure type student_t with components id and gpa */ student_t stulist[MAX_STU];/* declare 50 rows array of stulist */
47
Filling an array of structures with a function with the structured output argument
#include<stdio.h> #include<string.h> #define MAX_STU 3 #define NUM_PTS 10 /*declare structure type student_t with 2 components id and gpa */ typedef struct { int id; double gpa; }student_t; int scan_student(student_t *list_in); int main() { int i,j; /* declare 3 rows array of stulist */ student_t stulist[MAX_STU]; for (i=0; i <MAX_STU;++i ) { printf("Enter id, gpa:"); scan_student( &stulist[i] ); /* scan_student fills id and gpa */ } printf("\nYou have entered:\n"); for(i=0; i< MAX_STU; ++i) printf("%d %6.2f\n", stulist[i].id, stulist[i].gpa); return(0); int scan_student(student_t *list_in) /* output - address of student_t structure to fill */ { int result; result = scanf("%d%lf", &(*list_in).id, &(*list_in).gpa); if (result == 2) /* successfully scan all 2 members */ result = 1; else if (result != EOF) result = 0; /* error, no entry */ return (result); }
48
Filling an array of structures with a function that returns a structured value as the result
#include<stdio.h> #include<string.h> #define MAX_STU 3 #define NUM_PTS 10 /*declare structure type student_t with 2 components id and gpa */ typedef struct { int id; double gpa; }student_t; student_t get_student(void); int main() { int i,j; student_t stulist[MAX_STU]; /* declare 3 rows array of stulist */ for (i=0; i <MAX_STU;++i ) { printf("Enter id, gpa:"); stulist[i] = get_student(); /* get_student fills id and gpa */ } printf("\nYou have entered:\n"); for(i=0; i< MAX_STU; ++i) printf("%d %6.2f\n", stulist[i].id, stulist[i].gpa); return(0); student_t get_student(void) { student_t result; /* local structured variable*/ scanf("%d%lf", &result.id, &result.gpa); return (result);/* return structured value*/ } This function performs the same result as scan_student but shorter. Use & operator for components that are numeric or char type.
49
Arrays of Structures with String Components
Example, the string name[30] in this structure: typedef struct { char name[30]; double gpa; }student_t ; To declare an array of student_t type: student_t stulist[MAX_STU]; To fill the array using the get_student() function stulist[i] = sget_student(); using %s placeholder to print a string component for(i=0; i< MAX_STU; ++i) printf(“ %s\t%6.2f\n", stulist[i].name, stulist[i].gpa); String component is a pointer to char array, so, no need to use & operator if it is used in the scanf function student_t sget_student(void) { student_t result; scanf(“%s %lf", result.name, &result.gpa); return (result); } & not needed, it is a string component
50
Sorting a Structured Array
student_t sget_student(void) { student_t result; scanf("%s %lf", result.name, &result.gpa); return (result); } void struct_sort(student_t std[], int n) int i,j; student_t tmp; for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if(strcmp(std[i].name,std[j].name) > 0) { /*swap structured values*/ tmp=std[i]; std[i]=std[j]; std[j]=tmp; #include<stdio.h> #include<string.h> #define MAX_STU 3 typedef struct { char name[30]; double gpa; }student_t ; student_t sget_student(void); void struct_sort(student_t std[], int n); int main() { int i,j; student_t stulist[MAX_STU]; /* declare 3 rows array of stulist */ printf("Enter 3 student data\n"); for (i=0; i <MAX_STU;++i ) { printf("Enter name, gpa:"); stulist[i] = sget_student(); /* get_student fills name and gpa */ } printf("\nYou have entered:\n"); for(i=0; i< MAX_STU; ++i) printf("%s \t%6.2f\n", stulist[i].name, stulist[i].gpa); struct_sort(stulist, MAX_STU); printf("\nSorted List:\n"); return(0);
51
Union Type A union is a data structure that stores one of several types of data at a single location. Only one location is allocated for a union variable, irrespective of its size Defining a Union Union can be defined by the keyword union: union myUnion{ float var1; long var2; }; typedef union { int wears_wig; char color[20]; } hair_t; Here we have defined a union with the name myUnion and it has two members i.e. var1 of type float and var2 of type long Here we have defined a union with the name hair_t and it has two members i.e. wears_wig of type int and color of type sring
52
Union variable declaration
Declaring the Union we can declare the above defined union as. union myUnion{ int var1; long var2; }newUnion; So newUnion will be the variable of type myUnion. We can also declare the union as myUnion newUnion; Initializing the Union We can initialize the union in various ways union myUnion{ int var1; long var2; }newUnion={10.5}; or we can initialize it as newUnion.var1= 10.5 ;
53
Union variable declaration
Example of bit-field structure of a union union /* Defines a two-dimensional */ { /* array named screen */ struct { unsigned int icon : 8; unsigned color : 4; } window1; int screenval; } screen[25][80]; Nested unions can be declared anonymously when they are members of another structure or union. struct str { int a, b; union / * Unnamed union */ char c[4]; long l; float f; }; char c_array[10]; } my_str; . . . my_str.l == 0L; /* A reference to a field in the my_str union */ The screen array contains 2,000 elements. Each element of the array is an individual union with two members: window1 and screenval. The window1 member is a structure with two bit-field members, icon and color. The screenval member is an int. At any given time, each union element holds either the int represented by screenval or the structure represented by window1.
54
Union type access example
# include <stdio.h> #include<string.h> typedef union { int wears_wig; char color[20]; } hair_t; typedef struct{ int bald; hair_t h; }hair_info_t; union myUnion{ float var1; long var2; }; union myUnion newUnion; hair_info_t more_myhair; void print_union(); main( ) { newUnion.var1=12.25; more_myhair.bald=1; more_myhair.h.wears_wig=1; strcpy(more_myhair.h.color,"Black"); print_union(); newUnion.var2= ; more_myhair.bald=0; strcpy(more_myhair.h.color,"Brown"); more_myhair.h.wears_wig=0; return 0; } void print_union() printf("\nnewUnion.var = %f\n",newUnion.var1); printf("newUnion.var = %ld\n",newUnion.var2); printf("more_myhair.bald = %d\n",more_myhair.bald); printf("more_myhair.h.wears_wig = %d\n",more_myhair.h.wears_wig); printf("more_myhair.h.color = %s\n",more_myhair.h.color);
55
Array of Structures printf(“%d\n”, stulist[i].id);
Delaring an Array of Structures #define MAX_STU 50 #define NUM_PTS 10 /*declare structure type student_t with 2 components id and gpa */ typedef struct { int id; double gpa; }student_t; typedef struct{ double x, y; }point_t; int main() { student_t stulist[MAX_STU];/* declare 50 rows array of stulist */ point_t polygon[NUM_PTS]; /* declar 10 rows array of polygon points */ . . . Filling the entire array stulist (id and gpa) with data: for (i=0; i <MAX_STU;++i ) scan_student(&stulist[i]); /* scan_student fills id and gpa */ Displaying all the id numbers: for(i=0; i< MAX_STU; ++i) printf(“%d\n”, stulist[i].id); Array stulist after all components are filled
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.