Download presentation
Presentation is loading. Please wait.
1
Lecture 3: Arrays & Pointers
Object Oriented Programming (C++) Lecture 3: Arrays & Pointers
2
Contents 3.1 One-Dimensional Arrays 3.2 Two-Dimensional Arrays
3.3 Pointer
3
3.1 One-Dimensional Arrays
3.1.1 Declaring Arrays 3.1.2 Initialize Arrays in Declarations 3.1.3 How to Set Values 3.1.4 Passing Arrays as Arguments 3.1.5 Arrays of Records
4
3.1.1 Declaring Arrays One-dimensional array
A structured collection of components, with the same type, is gived a single name. Each component(array element) is accessed by an index that indicates the component’s position within the collection. The index is zero-based.
5
DataType ArrayName[ConstIntExpression];
3.1.1 Declaring Arrays Syntax template describing one-dimensional array declaration: ArrayDeclaration DataType ArrayName[ConstIntExpression];
6
3.1.2 Initialize Arrays in Declarations
Two form of intializing arrays 1. You learned in chapter 8 that c++ allows you to initialize a variable in its declaration; int delta=25; The value 25 is called an initializer. You also can initialize an array in its declaration, using a special syntax for the initializer . int age[5]={23,10,16,37,12};
7
3.1.2 Initialize Arrays in Declarations
Two form of initializing arrays 2. An interesting feature of C++ is that you are allowed to omit the size of an array when you initialize it in a declaration: float temperature[]={0,12.37,98.6};
8
3.1.3 How to Set Values Here is a loop to zero out our 100-
element alpha array(i is an int variable); for (i=0;i<100;i++) Alpha [i]=0.0; We could also write the first line as for(i=0;i<=99;i++)
9
3.1.4 Passing Arrays as Arguments
Base address The memory address of the first element of an array. It is impossible to pass a C++ array by value; Arrays are always passed by reference. Therefore, you never use & when declaring an array as a parameter. When an array is passed as an argument that’s base address.
10
3.1.4 Passing Arrays as Arguments
Example void ZeroOut(float arr[],int numElements) { int i; for(i=0;i<numElements;i++) arr[i]=0; }
11
3.1.4 Passing Arrays as Arguments
Example Void ZerOut(float[],int); …… int main() { float velocity[30]; float refractionAngle[9000]; ZeroOut(velocity,30); ZeroOut(refractionAngle,9000); }
12
3.1.5 Arrays of Records Arrays of Records const int MAX_STUDENTS=150;
enum GradeType{A,B,C,D,F}; Struct StudentRec { string stuName; float gpa; int examScore[4]; GradeType courseGrade; }; studentRec gradeBook[MAX_STUDENTS]; int count;
13
3.1.5 Arrays of Records Select member
An element of gradeBook is selected by an index. For example, gradeBook[2] is the third component in the array gradeBook. Each component of gradeBook is a record of type StudentRec. To access the course grade of the their student, we use the following expression: gradeBook[2].courseGrade
14
3.2 Two-Dimensional Arrays
A collection of components, all of the same type, structured in two dimensions. Each component is accessed by a pair of indexes that represent the component’s position in each dimension.
15
3.2.1 Initialize the Array Initialize the array
As with one-dimensional arrays, we can initialize a two-dimensional array either by initializing it in its declaration or by using assignment statements. If the array is summit, it is simplest to initialize it in its declaration.
16
3.2.1 Initialize the Array Initialize the Array
We can use the following declaration to initialize an array: int arr[2][3]= { {14,3,-5}, {0,46,7} };
17
3.2.2 Print the array Sum the row
Suppose we want to sum the row of number 3 in the array and print the result. We can do this easily with a for loop: total=0; for (col=0;col<NUM_COLS;col++) { total=total+arr[3][col]; cout<<“Row sum:”<<total<<endl; }
18
3.2.2 Print the array Sum the Columns
Suppose we want to sum and print each column. The code to perform this task follows. Again, we have generalized the code to sum only the portion of the array that contains valid data.
19
3.2.2 Print the array Sum the Columns
for (col=0;col<colsFilled;col++) { total=0; for (row=0;row<rowsFilled;row++) total=total+arr[row][col]; cout<<“Column sum:”<<total<<endl; }
20
3.2.2 Print the array Print the array
If we wish to print out an array with one row per line, then we have another case of row processing: #include<iomanip> …… for(row=0;col<NUM_COLS;col++) { cout<<setw(15)<<arr[row][col]; cout<<endl; }
21
3.3 Pointers Statements Since C++ is a compiling language, that means the variables in the program should be explained in advance in order to allocate memory for them before the program executing. C++ supports dynamic allocating memory mechanism. It is used by the pointer operators new and delete.
22
Pointers (cont.) pointer=new type; delete operator
new operator It is used to apply the memory for the variables, as follows: pointer=new type; delete operator It is used to free the memory to the operating system, as follows: delete pointer;
23
Pointers (cont.) Example: #include <iostream.h> void main() {
int *pi; cout<<“Before allocation pi is”<<pi<<endl; pi=new int; *pi=5; cout<<“After allocation pi is”<<pi<<endl; cout<<“The value is”<<*pi<<endl; delete pi; }
24
Pointers (cont.) Notes: A variable/object created by new exists until it is explicitly destroyed by delete. All the variables/objects created by new should be manually freed using delete. Otherwise, there will be memory leakage. We must pay attention to the pointer that should be the original allocation before we free the memory assigned to the pointer
25
Pointers (cont.) void main() { int *p= new int(3);
Wrong example: void main() { int *p= new int(3); cout<<*p<<endl; p+=3; // other operations delete p; }
26
Pointers (cont.) Correct example: void main() { int *p= new int(3);
int *q; q=p; cout<<*p<<endl; p+=3; // other operations delete q; }
27
Pointers (cont.) type *pointer_name =new type[size];
Arrays and pointers type *pointer_name =new type[size]; delete [] pointer_name ; The ‘‘plain’’ operator delete is used to delete individual objects; delete [] is used to delete arrays.
28
Pointers (cont.) delete p; delete []q; } Example 1: void f(int n) {
int *p=new int(n); //individual object int *q=new int[n]; //array //…… delete p; delete []q; }
29
The End
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.