Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 48

1

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.


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


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

– struct part Structure members


{
int modelnumber;
int partnumber;
Semicolon terminates
float cost; specifier
};

 2003 Prentice Hall, Inc. All rights reserved.


Structures (con’t)

• Defining a Structure variable Structure name


– The first statement in main()
Structure variable
part part1;
• 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.


6
1 // Fig. 3.1: fig01_01.cpp
2 // A simple structure program. Outline
3 #include <iostream>
4
5
6
7
• struct part // specify a structure
• {
10 int modelnumber; // ID number of widget
11 int partnumber; // ID number of widget part
• float cost; // cost of widget
• };
14 int main()
15 {
16 part part1; // define a structure variable
17 part1.modelnumber=6244;
18 part1.partnumber=373;
19 part1.cost=217.55;
20 cout << “\nModel " <<part1.modelnumber;
21 cout << “, part " <<part1.partnumber;
22 cout << “, costs $ " <<part1.cost;
23
24 return 0; // indicates successful termination
25 }

Model 6244, part 372, costs $217.55

 2003 Prentice Hall, Inc.


All rights reserved.
1 // Fig. 3.2: fig01_02.cpp 7
2 // Shows initialization of structure variables Outline
3 #include <iostream>
4
5
6
7
• struct part // specify a structure
• {
10 int modelnumber; // ID number of widget
11 int partnumber; // ID number of widget part
• float cost; // cost of widget
• };
14 int main()
15 {
16 part part1 = {6244, 373, 217.55}; // initialize variable
17 part part2; // define variable
18 // display first variable
19 cout << “\nModel " <<part1.modelnumber;
20 cout << “, part " <<part1.partnumber;
21 cout << “, costs $ " <<part1.cost;
22

23 part2 = part1; // assign first variable to second


// display second variable
24 cout << “\nModel " <<part2.modelnumber;
25 cout << “, part " <<part2.partnumber;
26 cout << “, costs $ " <<part2.cost;
27
28 return 0; // indicates successful termination
29 }

Model 6244, part 372, costs $217.55


Model 6244, part 372, costs $217.55

 2003 Prentice Hall, Inc.


All rights reserved.
Outline
Array of Structure
• 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 // Fig. 3.1: fig01_01.cpp 9
2 // A simple array of structure program. Outline
• #include <iostream>
4 #include <conio.h>
5
6
7
• struct abc // specify a structure
• {
• char code[10];
• char name[15];
12 float marks;
13 };
• 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}};
17 int i;
18 clrscr();
19 for (i=0; i<=2; i++)
20 cout<<“Code:”<<rec[i].code<<“\t”<<“Name:”<<rec[i].name<<“\t”
<<“Marks:”<<rec[i].marks<<endl;
21 getch();
22 return 0; // indicates successful termination
23 }

Code:man-1 Name:Asim Marks:45.9


Code:acc-1 Name:M.Rashid Marks:45.9
Code:fac-1 Name:M.Babar Marks:55.8
 2003 Prentice Hall, Inc.
All rights reserved.
10
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.
11
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.


12
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.


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

 2003 Prentice Hall, Inc. All rights reserved.


14
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.


15
1 // Fig. 5.28: fig05_28.cpp
2 // Using strcpy and strncpy.
Outline
3 #include <iostream.h>
4
<cstring> contains fig05_28.cpp
5
prototypes for strcpy and (1 of 2)
6
7 strncpy.
8 #include <string.h> // prototypes for strcpy and strncpy
9
10 int main()
11 {
12 char x[] = "Happy Birthday to You";
13 char y[ 25 ];
Copy entire string in array x
14 char z[ 15 ]; into array y.
15
16 strcpy( y, x ); // copy contents of x into y
17
18 cout << "The string in array x is: " << x
19
Copy first 14 characters
<< "\nThe string in array y is: " << y << '\n';
of
20 Appendarray x into array
terminating nullz. Note that
21 into this
z does not write terminating
// copy first 14 characters of x character.
22 strncpy( z, x, 14 ); // does not copynull character.
null character
23 z[ 14 ] = '\0'; // append '\0' to z's contents
24
25 cout << "The string in array z is: " << z << endl;

 2003 Prentice Hall, Inc.


All rights reserved.
16
26
27 return 0; // indicates successful termination
Outline
28 String to copy.
29 } // end main Copied string using strcpy.
Copied first 14fig05_28.cpp
characters
The string in array x is: Happy Birthday to You using strncpy. (2 of 2)
The string in array y is: Happy Birthday to You
The string in array z is: Happy Birthday fig05_28.cpp
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
17
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.


18
1 // Fig. 5.29: fig05_29.cpp
2 // Using strcat and strncat.
Outline
3 #include <iostream.h>
4
<cstring> contains fig05_29.cpp
5
prototypes for strcat and (1 of 2)
6
7 strncat.
8 #include <string.h> // prototypes for strcat and strncat
9
10 int main()
11 {
12 char s1[ 20 ] = "Happy ";
13 char s2[] = "New Year ";
14 char s3[ 40 ] = "";
Append s2 to s1.
15
16 cout << "s1 = " << s1 << "\ns2 = " << s2;
17
18 strcat( s1, s2 ); // concatenate s2 to s1
19
20 cout << "\n\nAfter strcat(s1, s2):\ns1 = " << s1
21 << "\ns2 = " << s2; Append first 6 characters of
22 s1 to s3.
23 // concatenate first 6 characters of s1 to s3
24 strncat( s3, s1, 6 ); // places '\0' after last character
25

 2003 Prentice Hall, Inc.


All rights reserved.
19
26 cout << "\n\nAfter strncat(s3, s1, 6):\ns1 = " << s1
27 << "\ns3 = " << s3; Append s1 to s3. Outline
28
29 strcat( s3, s1 ); // concatenate s1 to s3
fig05_29.cpp
30 cout << "\n\nAfter strcat(s3, s1):\ns1 = " << s1
(2 of 2)
31 << "\ns3 = " << s3 << endl;
32
33 return 0; // indicates successful termination fig05_29.cpp
34 output (1 of 1)
35 } // 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.
20
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.


21
1 // Fig. 5.32: fig05_32.cpp
2 // Using strlen.
Outline
3 #include <iostream.h>
4
<cstring> contains fig05_32.cpp
5
prototype for strlen. (1 of 1)
6
7
8 #include <string.h> // prototype for strlen
9
10 int main()
11 {
12 char *string1 = "abcdefghijklmnopqrstuvwxyz";
13 char *string2 = "four";
14 char *string3 = "Boston";
15
16 cout << "The length of \"" << string1
17 << "\" is " << strlen( string1 )
18 << "\nThe length of \"" << string2 Using strlen to determine
19 << "\" is " << strlen( string2 ) length of strings.
20 << "\nThe length of \"" << string3
21 << "\" is " << strlen( string3 ) << endl;
22
23 return 0; // indicates successful termination
24
25 } // 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.
22
One Dimensional Strings Outline

1 // Fig. 5.28: fig05_28.cpp fig05_32.cpp


2 // Using one dimensional array of string and strcpy
output (1 of 1)
3 #include <iostream.h>
4
5 #include <string.h> // prototypes for strcpy
6
7
8
9 const int MAX = 80;
10 int main()
11 {
12 char str1[] = "Happy Birthday to You";
13 char str2[ MAX ];
14
15
16 strcpy( str2, str1 ); // copy contents of str1 into str2
17 cout << endl;
• cout << “\nThe string in array str2 is: " << str2;
19 return 0; // indicates successful termination
•} // end main

The string in array str2 is: Happy Birthday to You

 2003 Prentice Hall, Inc.


All rights reserved.
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.


24
One and Two Dimensional Strings Outline

1 // Fig. 5.32: fig05_32.cpp fig05_32.cpp


2 // Array of strings
output (1 of 1)
3 #include <iostream.h>
4
5
6
7
• const int DAYS = 7; // number of strings in array
9 const int MAX = 10; // maximum size of each string
10 int main()
11 {
12 char star[DAYS][MAX] = {“Sunday”, “Monday”, “Tuesday”,
“Wednesday”, “Thursday”, “Friday”,
“Saturday” }; // array of strings
13 for (int j=0; j<DAYS; j++) // display every string
14 cout << star[j] << endl;
15
16 return 0; // indicates successful termination
17 } // end main

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
 2003 Prentice Hall, Inc.
Saturday All rights reserved.
Outline
Pointers and Arrays

• 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.
Outline
Pointers and Arrays

• 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.
Outline
Pointers and Arrays (cont)

• 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+1 p+2 p+3 p+4
p 200 202 204 206 208 ­­­­

x[0] x[1] x[2] x[3] x[4] ­­­­  2003 Prentice Hall, Inc.
All rights reserved.
An example of accessing array
elements using pointer notation
• 1 // arrpointer.cpp
• 2 // Program to print array elements using pointer notation
• 3 #include <iostream>
• 4 #include <conio.h>
• 5
• 6
• 7
• 8 int main()
• 9 {
• 10 int arr[5], *pp, i;
• 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 cout<<endl<<“Values from array” <<endl;
• 17 for (i=0;i<=4;i++)
• 18 cout<<*pp++<<endl; // increment pointer variable
• 19 getch();
• 20 return 0; // indicates successful termination
• 21 } // 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 <iostream>
• 4 #include <conio.h>
• 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.
Outline
Pointers and Strings

• 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”; //array of character type
char *string1 = “welcome”; //pointer variable of character
// type, pointer to string
 2003 Prentice Hall, Inc.
All rights reserved.
An example of string Outline
• 1 // string1.cpp
• 2 // A string is printed by printing its characters one by one
• 3 #include <iostream.h>
• 4
• 5
• 6
• 7
• 8
• 9 void pp(char*);
• 10 int main()
• 11 {
• 12 char st[] = “String”;
• 13
• 14 clrscr();
• 15 pp(st); // pass character array to pp
• 16 cout<<endl<<“ok”;
• 17 return 0; // indicates successful termination
• 18 } // end main

• 19 void pp(char *p) // pointer p points to start of


// string
• 20 {
• 21 while (*p != ‘\0’)
• 22 {
• 23 cout<<*p;
• 24 *p++; // increment pointer p
• 25 }
• 26 }
 2003 Prentice Hall, Inc.
All rights reserved.
Outline

String
ok

 2003 Prentice Hall, Inc.


All rights reserved.
Outline
Another example of string
• 1 // string2.cpp
• 2 // A program to find out the length of a string by using pointers
• 3 #include <iostream.h>
• 4 #include <conio.h>
• 5 #include <stdio.h>
• 6
• 7
• 8 int len(char*); // prototype
• 9
• 10 int main()
• 11 {
• 12 char st[25];
• 13 get function: used to input
• 14 clrscr(); data into a string variable
• 15 cout<<“Enter any string ? “;
• 16 gets(st); from keyboard; “cin”
// get caninto
input alsostring variable from keyboard
• 17 cout<<“length of stringbeisused, but characters are not
= “<<len(st);
• 18 return 0; // indicates stored when termination
successful space is press
}
• 19 } // end main
• 19 int len(char *s)
(i.e. appends ‘/0’ after that),
• 19 { int c=0; but “gets “ appends null
• 20 while (*s != ‘\0’) character, when Enter key is
• 21 {
• 22 c++;
pressed // increment “c” character counter
• 23 *s++;
• 24 }
• 25 return c; // return total number of characters
• 24 }

 2003 Prentice Hall, Inc.


All rights reserved.
Outline

Enter any string ? shehzad


length of string is = 7

 2003 Prentice Hall, Inc.


All rights reserved.
Outline
Another example of string
• 1 // string3.cpp
• 2 // A program to copy one string to another with pointers
• 3 #include <iostream.h>
• 4
• 5
• 6
• 7
• 8 void copystr(char*, char*); //prototype
• 9
• 10 int main()
• 11 {
• 12
• 13 char* str1= “Self-conquest is the greatest victory.”;
• 14 char str2[40]; //empty string
• 15 copystr(str2,str1) //copy str1 to str2
• 16 cout<<str2; //display str
• 17 }
• 18 void copystr(char* dest, char* src)
• 19 {
• 20 while (*src) //until null character,
• 21 *dest++ = *src++; //copy chars from src to dest
• 22 *dest = ‘/0’; //terminate dest
• 23 }
• 24
• 25
• 26 return 0; // indicates successful termination
• 27 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
Outline

Self-conquest is the greatest victory.

 2003 Prentice Hall, Inc.


All rights reserved.
Outline
Pointers and Strings (cont)

• 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.
40
Another example of pointers to Outline

1
strings
// Fig. 5.32: fig05_32.cpp fig05_32.cpp
2 // An Array of pointers to strings
output (1 of 1)
3 #include <iostream.h>
4
5
6
7
• const int DAYS = 7; // number of strings in array
9 const int MAX = 10; // maximum size of each string
10 int main()
11 {
12 char star[DAYS][MAX] = {“Sunday”, “Monday”, “Tuesday”,
“Wednesday”, “Thursday”, “Friday”,
“Saturday” }; // array of strings
13 for (int j=0; j<DAYS; j++) // display every string
14 cout << star[j] << endl;
15
16 return 0; // indicates successful termination
17 } // end main

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
 2003 Prentice Hall, Inc.
Saturday All rights reserved.
Outline
Another example of string
• 1 // string3.cpp
• 2 // A program to display string with pointer notation
• 3 #include <iostream.h>
• 4 #include <conio.h>
• 5
• 6
• 7
• 8 void dispstr(char*); //prototype
• 9
• 10 int main()
• 11 {
• 12 clrscr();
• 13 char str[] = “Idle people have the least leisure.”;
• 14 dispstr(str);
• 15 return 0; // indicates successful termination
• 15 } // end main
• 16 void dispstr(char* ps)
• 17 {
• 18 cout<<endl; //start on new line
• 19 while (*ps!=‘\0’) //until null character
• 20 cout <<*ps++; //print characters
• 21 }

Idle people have the least leisure.

 2003 Prentice Hall, Inc.


All rights reserved.
Outline
Pointers and Strings (cont)

• 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.
Outline
Pointers and Arrays

• 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]; //declare array of type int
int *pointer1; //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]; //store or assign address of 1st
//element of the array to pointer
 2003 Prentice Hall, Inc. All rights reserved.
45
An example of pointers and arrays Outline

1 // Fig. 5.32: fig05_32.cpp fig05_32.cpp


2 // Array accessed with pointers notation output (1 of 1)
3 #include <iostream>
4
5
6
7
• int main() {
• int intarray [5] = {31,54,77,52,93}; //array
10 for (int j=0; j<5; j++) //for each element
11
12 cout << endl << *(intarray+j); //print value
13
14 return 0; // indicates successful termination
15 } // end main

31
54
77
52
93
 2003 Prentice Hall, Inc.
All rights reserved.
Pointers and arrays Outline

(con’t)
• 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.
47
Another example of pointers and Outline
arrays
fig05_32.cpp
1 // Fig. 5.32: fig05_32.cpp output (1 of 1)
2 // Array accessed with pointers
3 #include <iostream>
4
5
6
7
• int main() {
• int intarray [5] = {31,54,77,52,93}; //array
• int* ptrint; //pointer to int
• ptrint = intarray; //points to intarray
12 for (int j=0; j<5; j++) //for each element
13
14 cout << endl << *(ptrint++); //print value
15
16 return 0; // indicates successful termination
17 } // end main

31
54
77
52
93
 2003 Prentice Hall, Inc.
All rights reserved.
Outline
Pointers and arrays (con’t)

• 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.

You might also like