Arrays Pointers, Dynamic Allocation & Strings
-
Upload
sarwan111291 -
Category
Documents
-
view
259 -
download
2
Transcript of Arrays Pointers, Dynamic Allocation & Strings
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
1/40
ARRAYS, POINTERS, DYNAMIC
ALLOCATION, STRINGS
CS-203 Object Oriented Programming 1
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
2/40
Arrays
Arrays of Objects
classname ob[3]; // declaring Array of Objects
for(i=0; i
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
3/40
Initializing Arrays
Long Form cl ob[3] = { cl(1), cl(2), cl(3) }; //initializing one
variable class
cl ob[3] = { cl(1, 2), cl(3, 4), cl(5, 6) }; //initializingtwo-variable class
Short Form (only for class having onevariable) cl ob[3] = {1, 2, 3};
CS-203 Object Oriented Programming 3
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
4/40
Pointer Variables Pointer variable: content is a memory address
Declaring Pointer Variables: Syntax
Examples:int *p;
char *ch;CS-203 Object Oriented Programming 4
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
5/40
Address Of Operator (&)
The ampersand, &, is called the address of
operator
The address of operator is a unary operatorthat returns the address of its operand
CS-203 Object Oriented Programming 5
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
6/40
Dereferencing Operator (*)
C++ uses * as the binary multiplication
operator and as a unary operator
When used as a unary operator, *
Is called dereferencing operator or indirection
operator
Refers to the object to which its operand (that is, a
pointer) points
CS-203 Object Oriented Programming 6
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
7/40
The following statement prints the value stored in the memory spacepointed to by p, which is the value ofx.
The following statement stores 55 in the memory location pointed to byp that is, in x.
Dereferencing Operator (*)
CS-203 Object Oriented Programming 7
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
8/40
Dereferencing Operator (*)
CS-203 Object Oriented Programming 8
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
9/40
Dereferencing Operator (*)
CS-203 Object Oriented Programming 9
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
10/40
Dereferencing Operator (*)
CS-203 Object Oriented Programming 10
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
11/40
Dereferencing Operator (*)
CS-203 Object Oriented Programming 11
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
12/40
You can also declare pointers to other data types, such as
classes.
student is an object of type studentType, and
studentPtr is a pointer variable of type studentType.
CS-203 Object Oriented Programming 12
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
13/40
This statement stores the address ofstudent in studentPtr.
This statement stores 3.9 in the component gpa of the object
student.
CS-203 Object Oriented Programming 13
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
14/40
In C++, the dot operator, ., has a higherprecedence than the dereferencing operator.
In the expression (*studentPtr).gpa, the
operator*
evaluates first and so the expression
*studentPtr evaluates first.
Because studentPtr is a pointer variable of
type studentType, *studentPtr, refers to
a memory space of type studentType, whichis a struct.
Therefore, (*studentPtr).gpa refers to
the component gpa of that struct.
CS-203 Object Oriented Programming 14
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
15/40
Consider the expression *studentPtr.gpa.
Because. (dot) has a higher precedence than *, theexpression studentPtr.gpa evaluates first.
The expression studentPtr.gpa would result in
syntax error as studentPtr is nota struct
variable, and so it has no such component as gpa.
In the expression(*studentPtr).gpa
, the
parentheses are important.
The expression (*studentPtr).gpa is a mixture
of pointer dereferencing and the class component
selection.
To simplify the accessing of class or struct
components via a pointer, C++ provides anotheroperator, called the member access operator arrow, -
>. The operator -> consists of two consecutive
symbols: a hyphen and the greater than sign.
CS-203 Object Oriented Programming 15
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
16/40
The syntax for accessing a class (struct)member using the operator -> is:
CS-203 Object Oriented Programming 16
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
17/40
Using Pointer to Object
Class cl {
int i;
public:
cl() { i=0; }
cl(int j) { i=j; }
int get_i() { return i; }};
int main()
{
cl ob[3] = {1, 2, 3};
cl *p;
int i;
p = ob; // get start of array
for(i=0; i
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
18/40
C++ does not automatically initialize variables.
Pointer variables must be initialized if you do not want them topoint to anything.
Pointer variables are initialized using the constant value 0, called
the null pointer.
The statement p = 0; stores the null pointer in p, that is,p points to nothing. Some programmers use the named constant
NULL to initialize pointer variables. The following two statements
are equivalent:
p = NULL;p = 0;
The number 0 is the only number that can be directly assigned to
a pointer variable.
CS-203 Object Oriented Programming 18
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
19/40
Dynamic Variables
Dynamic variables: created during execution
C++ creates dynamic variables using pointers
Two operators, new and delete, to create
and destroy dynamic variables
new and delete are reserved words
CS-203 Object Oriented Programming 19
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
20/40
The operator new has two forms: one to allocate a singlevariable, and another to allocate an array of variables. The syntaxto use the operatornew is:
where intExp is any expression evaluating to a positive
integer.
The operator new allocates memory (a variable) of thedesignated type and returns a pointer to itthat is, the address
of this allocated memory. Moreover, the allocated memory is
uninitialized.CS-203 Object Oriented Programming 20
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
21/40
The statement:
p = &x;
stores the address ofx in p. However, no new memory is
allocated.
Consider the following statement:
This statement creates a variable during program execution
somewhere in memory, and stores the address of the allocated
memory in p.
The allocated memory is accessed via pointer dereferencing, *p.
CS-203 Object Oriented Programming 21
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
22/40
CS-203 Object Oriented Programming 22
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
23/40
The operator new allocates memory space of a specific typeand returns the (starting) address of the allocated memory
space.
If the operator new is unable to allocate the required memoryspace, (for example, there is not enough memory space), then
it throws bad_alloc exception and if this exception is not
handled, it terminates the program with an error message.
CS-203 Object Oriented Programming 23
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
24/40
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
25/40
The statement in Line 2 stores 54 into the memory space that p pointsto.
The statement in Line 3 executes, which allocates a memory space of
type int and stores the address of the allocated memory space into
p. Suppose the address of this allocated memory space is 1800.
CS-203 Object Oriented Programming 25
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
26/40
The statement in Line 4 stores73 into the memory space that p
points.
CS-203 Object Oriented Programming 26
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
27/40
What happened to the memory space 1500 that p was pointing toafter execution of the statement in Line 1?
After execution of the statement in Line 3, p points to the new memory
space at location 1800.
The previous memory space at location 1500 is now inaccessible.
The memory space 1500 remains as marked allocated. In other words,it cannot be reallocated.
This is called memory leak.
Imagine what would happen if you execute statements such as Line 1 a
few thousand times, or a few million times. There will be a good (bad)
amount of memory leak. The program might then run out of memory
spaces for data manipulation, and eventually result in an abnormal
termination of the program.
How do we avoidmemory leaks?
CS-203 Object Oriented Programming 27
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
28/40
When a dynamic variable is no longer needed, it can be destroyed; thatis, its memory can be deallocated.
The C++, the operator delete is used to destroy dynamic variables.
The syntax to use the operator delete has two forms:
CS-203 Object Oriented Programming 28
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
29/40
An array created during the execution of a program is called a
dynamic array.
To create a dynamic array, we use the second form of the new operator.
The statement:
int *p;declares p to be a pointer variable of type int. The statement:
p = new int[10];
allocates 10 contiguous memory locations, each of type int, and stores
the address ofthe first memory location into p. In other words, theoperator new creates an array of10 components of type int; it returns
the base address of the array, and the assignment operator stores the
base address of the array into p.
CS-203 Object Oriented Programming 29
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
30/40
The statement:
*p = 25;
stores 25 into the first memory location.
The statements:
p++; //p points to the next array component*p = 35;
store 35 into the second memory location.
By using the increment and decrement operations, you can access the
components of the array. Of course, after performing a few increment operations, it is possible to
lose track of the first array component.
CS-203 Object Oriented Programming 30
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
31/40
C++ allows us to use array notation to access these memory locations.
The statements:
p[0] = 25;
p[1] = 35;
store 25 and 35 into the first and second array components,
respectively.
The following for loop initializes each array component to 0:
for (j = 0; j < 10; j++)p[j] = 0;
where j is an int variable.
CS-203 Object Oriented Programming 31
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
32/40
The statement:
int list[5];
declares list to be an array of5 components.
CS-203 Object Oriented Programming 32
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
33/40
Because the value oflist, which is 1000, is a memory address, list is a
pointer variable.
The value stored in list (1000) cannot be altered during program execution.
That is, the value oflist is constant. An array name is a constant pointer.
Therefore, the increment and decrement operations cannot be applied to list.
CS-203 Object Oriented Programming 33
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
34/40
Ifp is a pointer variable of type int, then the statement:
p = list;
copies the value oflist (1000, the base address of the array) into p.
We can perform increment and decrement operations on p.
CS-203 Object Oriented Programming 34
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
35/40
Pointer to Array of Objects
1. #include
2. #include
3. #include
4. using namespace std;
5. class balance {
6. double cur_bal;7. char name[80];
8. public:
9. balance(double n, char *s) {
10. cur_bal = n;
11. strcpy(name, s);
12. }13. balance() {} // parameterless constructor
14. ~balance() {
15. cout
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
36/40
Pointer to Array of Objects
1. int main()2. {
3. balance *p;
4. char s[80];
5. double n;
6. int i;
7. try {8. p = new balance [3]; // allocate entire
array
9. } catch (bad_alloc xa) {
10. cout
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
37/40
Array of Pointers to Objects
1. Int main()
2. {
3. balance p[100];
4. Int n=0; char choice;
5. do6. {
7. p[n]=new balance;
8. P[n]->set();
9. n++;
10. coutchoice;
12. }
13. While(choice==Y);
14. For(int i=0; iget_bal();
17. }
18. Cout
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
38/40
String Class
Standard C++ includes a new class called
string.
No need to worry about size of the array.
More efficient to use.
Overloaded operators (+, =; e.g S1=S2+S3)
CS-203 Object Oriented Programming 38
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
39/40
String Class
Header file: #include
Declaration: string Name;
Reading Embedded blanks:
getline (cin , Name);
Reading multiple lines:
Getline (cin, address, $) //reads multiple lines till $ isentered as terminating character.
CS-203 Object Oriented Programming 39
-
8/6/2019 Arrays Pointers, Dynamic Allocation & Strings
40/40
Modifying string objects
#include #include
using namespace std;
int main ()
{
string s1 (Nothing is impossible);string s2(Everything);
string s3(with perseverence);
s1.erase(11, 2); //erases a substring from position 11 of length 2. Now string s1 becomes Nothingis possible
s1.replace(0,7,s2); //replaces string s1 with substring s2 at 0th position by replacing 7 character.Now string s1 becomes Everything is possible
s1.insert(23, s3); //inserts string s3 at index 23 of string s1
s1.append(3, !); // appends ! 3 times at the end of string s1
return 0;
}
CS 203 Obj O i d P i 40