2003 Prentice Hall, Inc. All Rights Reserved

  • Uploaded by: api-3737023
  • 0
  • 0
  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View 2003 Prentice Hall, Inc. All Rights Reserved as PDF for free.

More details

  • Words: 4,476
  • Pages: 48
Week 3-4 -Structures, Strings and Pointers Outline • Structures • Array of Structure • Strings • String Manipulation Functions of the String­handling Library • One and Two Dimensional Strings • Pointers and Arrays • Pointers and Strings

 2003 Prentice Hall, Inc. All rights reserved.

1

Structures • Structures – A collection of simple variables – Variables can be of different types or heterogeneous elements – The data items in a structure are called the members of the structure

• Structure vs Array – Structure is collection of heterogenous data elements – Array is collection of homogenous data elements

• Structure vs Class (comparsion) – Structure is a collection of data – Class is a collection of data and functions  2003 Prentice Hall, Inc. All rights reserved.

Structures (con’t) Structure name

• Specifying the structure Braces delimit structure members

Keyword “struct” – The structure specifier tells how the structure is organized: it specifies what members the structure will have. Here it is: – struct part Structure members

{ int modelnumber; int partnumber; float cost; };

 2003 Prentice Hall, Inc. All rights reserved.

Semicolon terminates specifier

Structures (con’t) • Defining a Structure variable – The first statement in main() part part1;

Structure name Structure variable

• Accessing Structure Members Structure variable

– Members can be accessed using “dotStructure operator” member part1.modelnumber = 6244; Dot operator

 2003 Prentice Hall, Inc. All rights reserved.

Structures (con’t) • Initializing Structure variables – The part1 structure variable’s members are initialized when the variable is defined: part part1 = { 6244 , 373 , 217.55 }; cout << “\n Model “ << part1.modelnumber; cout << “, part ” << part1.partnumber; cout << “, costs $” << part1.cost; Output Model 6244, part 373, costs $217.55

 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 • • 10 11 • • 14 15 16 17 18 19 20 21 22 23 24 25

// Fig. 3.1: fig01_01.cpp // A simple structure program. #include

Outline

struct part // specify a structure { int modelnumber; // ID number of widget int partnumber; // ID number of widget part float cost; // cost of widget }; int main() { part part1; // define a structure variable part1.modelnumber=6244; part1.partnumber=373; part1.cost=217.55; cout << “\nModel " <<part1.modelnumber; cout << “, part " <<part1.partnumber; cout << “, costs $ " <<part1.cost; return 0; }

// indicates successful termination

Model 6244, part 372, costs $217.55

 2003 Prentice Hall, Inc. All rights reserved.

6

1 2 3 4 5 6 7 • • 10 11 • • 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

// Fig. 3.2: fig01_02.cpp // Shows initialization of structure variables #include

struct part { int modelnumber; int partnumber; float cost; }; int main() { part part1 = {6244, 373, 217.55}; part part2;

Outline

// specify a structure // ID number of widget // ID number of widget part // cost of widget

// initialize variable // define variable // display first variable

cout << “\nModel " <<part1.modelnumber; cout << “, part " <<part1.partnumber; cout << “, costs $ " <<part1.cost; part2 = part1;

// assign first variable to second // display second variable cout << “\nModel " <<part2.modelnumber; cout << “, part " <<part2.partnumber; cout << “, costs $ " <<part2.cost; return 0; }

// indicates successful termination

Model 6244, part 372, costs $217.55 Model 6244, part 372, costs $217.55

 2003 Prentice Hall, Inc. All rights reserved.

7

Array of Structure • • •

Outline

Like an array, the data into array of structure variables can also be assigned at the time of its declaration For example: In the following example, the structure variable “rec” has three elements The data of fields of each record is enclosed in braces and is separated by commas struct abc { char code[10]; char name[15]; float marks; }; void main() { abc rec[3]= {{“man-1”,”Asim”,45.9}, {“acc-1”,”M.Rashid”,45.9}, {“fac-1”,”M.Babar”,55.8}};  2003 Prentice Hall, Inc. All rights reserved.

1 2 • 4 5 6 7 • • • • 12 13 • • • 17 18 19 20 21 22 23

// Fig. 3.1: fig01_01.cpp // A simple array of structure program. #include #include

Outline

struct abc // specify a structure { char code[10]; char name[15]; float marks; }; int main() { abc rec[3]= {{“man-1”,”Asim”,45.9}, //array of structure {“acc-1”,”M.Rashid”,45.9}, {“fac-1”,”M.Babar”,55.8}}; int i; clrscr(); for (i=0; i<=2; i++) cout<<“Code:”<
Code:man-1 Code:acc-1 Code:fac-1

Name:Asim Name:M.Rashid Name:M.Babar

Marks:45.9 Marks:45.9 Marks:55.8

 2003 Prentice Hall, Inc. All rights reserved.

9

Fundamentals of Characters and Strings • Character constant – Integer value represented as character in single quotes – 'z' is integer value of z • 122 in ASCII

• String – Series of characters treated as single unit – Can include letters, digits, special characters +, -, * ... – String literal (string constants) • Enclosed in double quotes, for example: "I like C++"

– Array of characters, ends with null character '\0' – String is constant pointer • Pointer to string’s first character – Like arrays  2003 Prentice Hall, Inc. All rights reserved.

10

Fundamentals of Characters and Strings • String assignment – Character array • char color[] = "blue"; – Creates 5 element char array color • last element is '\0'

– Variable of type char * • char *colorPtr = "blue"; – Creates pointer colorPtr to letter b in string “blue” • “blue” somewhere in memory

– Alternative for character array • char color[] = { ‘b’, ‘l’, ‘u’, ‘e’, ‘\0’ };

 2003 Prentice Hall, Inc. All rights reserved.

11

Fundamentals of Characters and Strings • Reading strings – Assign input to character array word[ 20 ] cin >> word • Reads characters until whitespace or EOF

 2003 Prentice Hall, Inc. All rights reserved.

12

String Manipulation Functions of the String-handling Library • String handling library provides functions to – Manipulate string data – Compare strings – Search strings for characters and other strings

 2003 Prentice Hall, Inc. All rights reserved.

13

String Manipulation Functions of the String-handling Library • Copying strings – char *strcpy(const char *s1, const char *s2 ) • Copies second argument into first argument – First argument must be large enough to store string and terminating null character

– char *strncpy(const char *s1, const char *s2, size_t n ) • Specifies number of characters to be copied from string into array • Does not necessarily copy terminating null character

 2003 Prentice Hall, Inc. All rights reserved.

14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// Fig. 5.28: fig05_28.cpp // Using strcpy and strncpy. #include

Outline contains prototypes for strcpy and strncpy.

#include <string.h>

// prototypes for strcpy and strncpy

int main() { char x[] = "Happy Birthday to You"; Copy entire string char y[ 25 ]; into array y. char z[ 15 ]; strcpy( y, x );

fig05_28.cpp (1 of 2)

in array x

// copy contents of x into y

cout << "The string in array x is: " << x Copy first 14 characters << "\nThe string in array y is: " << y << '\n';

of array x into array Append terminating nullz. Note that // copy first 14 characters of x character. into this z does not write terminating character. strncpy( z, x, 14 ); // does not copynull null character z[ 14 ] = '\0';

// append '\0' to z's contents

cout << "The string in array z is: " << z << endl;

 2003 Prentice Hall, Inc. All rights reserved.

15

26 27 28 29

return 0;

// indicates successful termination

} // end main

The string in array x is: Happy Birthday to You The string in array y is: Happy Birthday to You The string in array z is: Happy Birthday

Outline String to copy. Copied string using strcpy. Copied first 14fig05_28.cpp characters (2 of 2) using strncpy. fig05_28.cpp output (1 of 1)

 2003 Prentice Hall, Inc. All rights reserved.

16

String Manipulation Functions of the String-handling Library • Concatenating strings – char *strcat (const char *s1, const char *s2) • Appends second argument to first argument • First character of second argument replaces null character terminating first argument • Ensure first argument large enough to store concatenated result and null character

– char *strncat( const char *s1, const char *s2, size_t n ) • Appends specified number of characters from second argument to first argument • Appends terminating null character to result

 2003 Prentice Hall, Inc. All rights reserved.

17

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// Fig. 5.29: fig05_29.cpp // Using strcat and strncat. #include

Outline contains prototypes for strcat and strncat.

#include <string.h>

fig05_29.cpp (1 of 2)

// prototypes for strcat and strncat

int main() { char s1[ 20 ] = "Happy "; char s2[] = "New Year "; char s3[ 40 ] = "";

Append s2 to s1.

cout << "s1 = " << s1 << "\ns2 = " << s2; strcat( s1, s2 );

// concatenate s2 to s1

cout << "\n\nAfter strcat(s1, s2):\ns1 = " << s1 Append first 6 characters << "\ns2 = " << s2;

of

s1 to s3.

// concatenate first 6 characters of s1 to s3 strncat( s3, s1, 6 ); // places '\0' after last character

 2003 Prentice Hall, Inc. All rights reserved.

18

26 27 28 29 30 31 32 33 34 35

cout << "\n\nAfter strncat(s3, s1, 6):\ns1 = " << s1 Append s1 to s3. << "\ns3 = " << s3;

Outline

strcat( s3, s1 ); // concatenate s1 to s3 cout << "\n\nAfter strcat(s3, s1):\ns1 = " << s1 << "\ns3 = " << s3 << endl;

fig05_29.cpp (2 of 2)

return 0;

fig05_29.cpp output (1 of 1)

// indicates successful termination

} // end main

s1 = Happy s2 = New Year After strcat(s1, s2): s1 = Happy New Year s2 = New Year After strncat(s3, s1, 6): s1 = Happy New Year s3 = Happy After strcat(s3, s1): s1 = Happy New Year s3 = Happy Happy New Year

 2003 Prentice Hall, Inc. All rights reserved.

19

String Manipulation Functions of the String-handling Library • Determining string lengths – size_t strlen( const char *s ) • Returns number of characters in string – Terminating null character not included in length

 2003 Prentice Hall, Inc. All rights reserved.

20

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// Fig. 5.32: fig05_32.cpp // Using strlen. #include

Outline contains prototype for strlen.

#include <string.h>

fig05_32.cpp (1 of 1)

// prototype for strlen

int main() { char *string1 = "abcdefghijklmnopqrstuvwxyz"; char *string2 = "four"; char *string3 = "Boston"; cout << << << << << <<

"The length of \"" << string1 "\" is " << strlen( string1 ) "\nThe length of \"" << string2 "\" is " << strlen( string2 ) "\nThe length of \"" << string3 "\" is " << strlen( string3 ) << endl;

return 0;

Using strlen to determine length of strings.

// indicates successful termination

} // end main

The length of "abcdefghijklmnopqrstuvwxyz" is 26 The length of "four" is 4 The length of "Boston" is 6

 2003 Prentice Hall, Inc. All rights reserved.

21

One Dimensional Strings 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 • 19 •}

// Fig. 5.28: fig05_28.cpp // Using one dimensional array of string and strcpy #include #include <string.h>

Outline fig05_32.cpp output (1 of 1)

// prototypes for strcpy

const int MAX = 80; int main() { char str1[] = "Happy Birthday to You"; char str2[ MAX ];

strcpy( str2, str1 ); // copy contents of str1 into str2 cout << endl; cout << “\nThe string in array str2 is: " << str2; return 0; // indicates successful termination // end main

The string in array str2 is: Happy Birthday to You

 2003 Prentice Hall, Inc. All rights reserved.

22

23

One and Two Dimensional Strings • In this example, we have two dimensional array of strings. – First dimension of this array, DAYS, tells how many strings are in the array. – Second dimension of this array, MAX, specifies the maximum length of the strings (9 characters for “Wednesday” plus the terminating null makes 10).

 2003 Prentice Hall, Inc. All rights reserved.

One and Two Dimensional Strings 1 2 3 4 5 6 7 • 9 10 11 12

13 14 15 16 17

// Fig. 5.32: fig05_32.cpp // Array of strings #include

Outline fig05_32.cpp output (1 of 1)

const int DAYS = 7; // number of strings in array const int MAX = 10; // maximum size of each string int main() { char star[DAYS][MAX] = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” }; // array of strings for (int j=0; j
Sunday Monday Tuesday Wednesday Thursday Friday Saturday

 2003 Prentice Hall, Inc. All rights reserved.

24

Pointers and Arrays

Outline

• An array consists of consecutive locations in the computer memory • To access an array, the memory location of first element of the array is accessed using pointer variable • The pointer is then incremented to access other elements of the array • The pointer is increased in value according to the size of the elements of the array

 2003 Prentice Hall, Inc. All rights reserved.

Pointers and Arrays

Outline

• When an array is declared, the array name points to the starting address of the array. For example, consider the following example: int x[5]; int *p;

• The array “x” is of type “int” and “p” is a pointer variable of type “int” • For example: if the memory address of first element of the array is to be assigned to a pointer, the statement is written as: p = &x[0];

 2003 Prentice Hall, Inc. All rights reserved.

Pointers and Arrays (cont)

Outline

• Suppose the location of first element in memory is 200, i.e. the value of pointer variable “p” is 200 and it refers to an integer variable. When the following statement is executed p = p+1;

//i.e. 200+1*2=202

• The logical diagram of an integer type array “x” and pointer variable “p” that points to the elements of the array “x” is given below: p

p

p+1

p+2

p+3

200

202

204

x[0]

x[1]

x[2]

206

p+4 208

­­­­

x[3]

x[4]

­­­­  2003 Prentice Hall, Inc.

x

All rights reserved.

An example of accessing array elements using pointer notation • • • • • • • • • • • •

1 2 3 4 5 6 7 8 9 10 11 12

• • • • • • • • •

variable 13 14 15 16 17 18 19 20 21 }

// arrpointer.cpp // Program to print array elements using pointer notation #include #include

int main() { int arr[5], *pp, i; clrscr(); pp = arr;

// assign each element of an // array to pointer

cout<<“Enter values into an array”<<endl; for (i=0;i<=4;i++) cin>>arr[i]; cout<<endl<<“Values from array” <<endl; for (i=0;i<=4;i++) cout<<*pp++<<endl; // increment pointer variable getch(); return 0; // indicates successful termination // end main

Outline

Enter values into an array 10 20 30 40 50 Values from array 10 20 30 40 50

 2003 Prentice Hall, Inc. All rights reserved.

An example of accessing arrayOutline elements using pointer notation • • • • • • • • • • • • • • • • • • • • • • • •

1 // arrpointer1.cpp 2 // Print array elements and find maximum value using pointer notation 3 #include 4 #include 5 6 7 int i,u; // global variables 8 int main() 9 { 10 int arr[5], *pp, i, max; 11 clrscr(); 12 pp = arr; // assign each element of an // array to pointer variable 13 cout<<“Enter values into an array “<<endl; 14 for (i=0;i<=4;i++) 15 cin>>arr[i]; 16 max = *pp; // set first element to max 17 for (i=0;i<=4;i++) 18 { *pp++; // increment pointer variable 19 if (max<*pp) 20 max = *pp; } 21 cout<<“Maximum value is = “<<max; 22 getch(); 23 return 0; // indicates successful termination 24 } // end main

 2003 Prentice Hall, Inc. All rights reserved.

Outline

Enter values into an array 10 20 30 40 50 Maximum value is = 50

 2003 Prentice Hall, Inc. All rights reserved.

Pointers and Strings

Outline

• A string is a sequence of characters • A string type variable is declared in the same manner as an array type variable is declared, this is because a string is an array of character type variables • Since a string is like an array, pointer variables can also be used to access it • For example: char string1[] = “welcome”; char *string1 = “welcome”;

//array of character type //pointer variable of character // type, pointer to string  2003 Prentice Hall, Inc. All rights reserved.

An example of string • • • • • • • • • • • • • • • • • •

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

// string1.cpp // A string is printed by printing its characters one by one #include



19

void pp(char *p)

• • • • • • •

20 21 22 23 24 25 26

Outline

void pp(char*); int main() { char st[] = “String”; clrscr(); pp(st); // pass character array to pp cout<<endl<<“ok”; return 0; // indicates successful termination } // end main // pointer p points to start of // string

{ while (*p != ‘\0’) { cout<<*p; *p++; }

// increment pointer p

}

 2003 Prentice Hall, Inc. All rights reserved.

Outline

String ok

 2003 Prentice Hall, Inc. All rights reserved.

Another example of string • • • • • • • • • • • • • • • • • • • • • • • • • • • •

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 19 19 20 21 22 23 24 25 24

Outline

// string2.cpp // A program to find out the length of a string by using pointers #include #include #include <stdio.h>

int len(char*);

// prototype

int main() { char st[25];

get function: used to input clrscr(); data into a string variable cout<<“Enter any string ? “; from keyboard; “cin” caninto alsostring gets(st); // get input beisused, but characters are not cout<<“length of string = “<
variable from keyboard

“c” character counter

// return total number of characters

 2003 Prentice Hall, Inc. All rights reserved.

Outline Enter any string ? shehzad length of string is = 7

 2003 Prentice Hall, Inc. All rights reserved.

Another example of string • • • • • • • • • • • • • • • • • • • • • • • • • • •

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

Outline

// string3.cpp // A program to copy one string to another with pointers #include

void copystr(char*, char*);

//prototype

int main() { char* str1= “Self-conquest is the greatest victory.”; char str2[40]; //empty string copystr(str2,str1) //copy str1 to str2 cout<<str2; //display str } void copystr(char* dest, char* src) { while (*src) //until null character, *dest++ = *src++; //copy chars from src to dest *dest = ‘/0’; //terminate dest }

return 0; // indicates successful termination } // end main

 2003 Prentice Hall, Inc. All rights reserved.

Outline

Self-conquest is the greatest victory.

 2003 Prentice Hall, Inc. All rights reserved.

Pointers and Strings (cont)

Outline

• Here in this program, the program calls the function copystr() to copy str1 to str2. In this function the expression *dest++ = *src++;

• This expression takes the value at the address pointed to by “src” and places it in the address pointed to by “dest” • Both pointers are then incremented, so the next time through the loop the next character will be transferred • The loop terminates when a null character is found in “src” at this point a null is inserted in “dest” and the function returns

 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 • 9 10 11 12

13 14 15 16 17

Another example of pointers to strings // Fig. 5.32: fig05_32.cpp // An Array of pointers to strings #include

const int DAYS = 7; const int MAX = 10; int main()

Outline fig05_32.cpp output (1 of 1)

// number of strings in array // maximum size of each string

{ char star[DAYS][MAX] = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” }; // array of strings for (int j=0; j
Sunday Monday Tuesday Wednesday Thursday Friday Saturday

 2003 Prentice Hall, Inc. All rights reserved.

40

Outline

Another example of string • • • • • • • • • • • • • • • • • • • • • •

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 15 16 17 18 19 20 21

// string3.cpp // A program to display string with pointer notation #include #include

void dispstr(char*);

//prototype

int main() { clrscr(); char str[] = “Idle people have the least leisure.”; dispstr(str); return 0; // indicates successful termination } // end main void dispstr(char* ps) { cout<<endl; //start on new line while (*ps!=‘\0’) //until null character cout <<*ps++; //print characters }

Idle people have the least leisure.

 2003 Prentice Hall, Inc. All rights reserved.

Pointers and Strings (cont)

Outline

• In the previous example, the array address “str” is used as the argument in the call to function “dispstr( )” • This address is a constant, but since it is passed by value, a copy of it is created in “dispstr( )” • This copy is a pointer “ps”, the pointer can be change as function parameter, so the function increments “ps” to display the string • The expression “*ps++” returns the successive characters of the string • The loop cycles until it finds the null character (‘\0’) at the end of the string  2003 Prentice Hall, Inc. All rights reserved.

Pointers and Arrays

Outline

• There is a close relationship b/w pointers and arrays • An element of an array is accessed by its subscript value or index value, enclosed in square brackets • In advanced programming, arrays are accessed using pointers • An array consists of consecutive memory locations • To access an array, the memory location of the first element of the array is accessed using pointer variable • The pointer is then incremented to access other elements of the array  2003 Prentice Hall, Inc. All rights reserved.

44

Pointers and Arrays (cont) • When an array is declared, the array name points to the starting address of the array • For example: int array1[3]; int *pointer1;

//declare array of type int //pointer to array1 of type int

• To store the address of first element or starting address of array, the following statement is used: pointer1=array1

//store or assign address to pointer

• Or to store or assign address of first element to pointer variable, the following statement is used: pointer1=&array1[0];  2003 Prentice Hall, Inc. All rights reserved.

//store or assign address of 1st //element of the array to pointer

An example of pointers and arrays 1 2 3 4 5 6 7 • • 10 11 12 13 14 15

// Fig. 5.32: fig05_32.cpp // Array accessed with pointers notation #include

Outline fig05_32.cpp output (1 of 1)

int main() { int intarray [5] = {31,54,77,52,93}; //array for (int j=0; j<5; j++) //for each element cout << endl << *(intarray+j);

//print value

return 0; // indicates successful termination } // end main

31 54 77 52 93

 2003 Prentice Hall, Inc. All rights reserved.

45

Pointers and arrays (con’t)

Outline

• In the previous example, the expression *(intarray+j) • We know that the name of an array is its address • The array starts off with its initial address (memory location) • Thus the expression (intarray+j) is thus an address with some value of “j” is added to it • For example, the value of “j” is 3, thus the address of “intarray” plus 3 gives us fourth integer of an array • But we want value of this fourth array element not address, so we use “*” operator, thus gives us 52  2003 Prentice Hall, Inc. All rights reserved.

Another example of pointers and arrays 1 2 3 4 5 6 7 • • • • 12 13 14 15 16 17

// Fig. 5.32: fig05_32.cpp // Array accessed with pointers #include

Outline fig05_32.cpp output (1 of 1)

int main() { int intarray [5] = {31,54,77,52,93}; //array int* ptrint; //pointer to int ptrint = intarray; //points to intarray for (int j=0; j<5; j++) //for each element cout << endl << *(ptrint++);

//print value

return 0; // indicates successful termination } // end main

31 54 77 52 93

 2003 Prentice Hall, Inc. All rights reserved.

47

Pointers and arrays (con’t)

Outline

• In the previous example, the array starts off with an initial address (memory location) • The pointer “ptrint” is pointer to intarray of int type • The “ptrint” is starts off with same address value as “intarray”, thus allowing the first array element, intarray[0], which has the value 31, using “*” operator. • Then “ptrint” variable is incremented and points to intarray[1] which has the value 54, using “*” operator. • Similarly all the elements of an array are accessed and printed

 2003 Prentice Hall, Inc. All rights reserved.

Related Documents