Sie sind auf Seite 1von 40

ARRAYS, POINTERS, DYNAMIC

ALLOCATION, STRINGS

CS-203 Object Oriented Programming 1


Arrays
• Arrays of Objects

classname ob[3]; // declaring Array of Objects


for(i=0; i<3; i++)
ob[i].set_i(); //calling function using array of object

CS-203 Object Oriented Programming 2


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) }; //initializing
two-variable class

• Short Form (only for class having one


variable)
– cl ob[3] = {1, 2, 3};

CS-203 Object Oriented Programming 3


Pointer Variables
• Pointer variable: content is a memory address
• Declaring Pointer Variables: Syntax

• Examples:
int *p;
char *ch;
CS-203 Object Oriented Programming 4
Address Of Operator (&)
• The ampersand, &, is called the address of
operator

• The address of operator is a unary operator


that returns the address of its operand

CS-203 Object Oriented Programming 5


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


Dereferencing Operator (*)

The following statement prints the value stored in the memory space
pointed to by p, which is the value of x.

The following statement stores 55 in the memory location pointed to by


p that is, in x.

CS-203 Object Oriented Programming 7


Dereferencing Operator (*)

CS-203 Object Oriented Programming 8


Dereferencing Operator (*)

CS-203 Object Oriented Programming 9


Dereferencing Operator (*)

CS-203 Object Oriented Programming 10


Dereferencing Operator (*)

CS-203 Object Oriented Programming 11


• 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
• This statement stores the address of student in studentPtr.

• This statement stores 3.9 in the component gpa of the object


student.

CS-203 Object Oriented Programming 13


• In C++, the dot operator, ., has a higher
precedence 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, which
is a struct.

• Therefore, (*studentPtr).gpa refers to


the component gpa of that struct.
CS-203 Object Oriented Programming 14
• Consider the expression *studentPtr.gpa.
Because. (dot) has a higher precedence than *, the
expression studentPtr.gpa evaluates first.
• The expression studentPtr.gpa would result in
syntax error as studentPtr is not a 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 another
operator, 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


The syntax for accessing a class (struct)
member using the operator -> is:

CS-203 Object Oriented Programming 16


Using Pointer to Object
Class cl { int main()
int i; {
public: cl ob[3] = {1, 2, 3};
cl() { i=0; } cl *p;
cl(int j) { i=j; } int i;
int get_i() { return i; }
}; p = ob; // get start of array
for(i=0; i<3; i++) {
cout << p->get_i() << "\n";
p++; // point to next object
}

return 0;
}

CS-203 Object Oriented Programming 17


• C++ does not automatically initialize variables.
• Pointer variables must be initialized if you do not want them to
point 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
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


• The operator new has two forms: one to allocate a single
variable, and another to allocate an array of variables. The syntax
to use the operator new is:

where intExp is any expression evaluating to a positive


integer.

• The operator new allocates memory (a variable) of the


designated type and returns a pointer to it—that is, the address
of this allocated memory. Moreover, the allocated memory is
uninitialized.
CS-203 Object Oriented Programming 20
• The statement:
p = &x;
stores the address of x 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


CS-203 Object Oriented Programming 22
• The operator new allocates memory space of a specific type
and returns the (starting) address of the allocated memory
space.
• If the operator new is unable to allocate the required memory
space, (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


• The statement in Line 1 allocates memory space of type int and
stores the address of the allocated memory space into p. Suppose
that the address of allocated memory space is 1500.

CS-203 Object Oriented Programming 24


• The statement in Line 2 stores 54 into the memory space that p points
to.

• 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


• The statement in Line 4 stores 73 into the memory space that p
points.

CS-203 Object Oriented Programming 26


• What happened to the memory space 1500 that p was pointing to
after 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 avoid memory leaks?
CS-203 Object Oriented Programming 27
• When a dynamic variable is no longer needed, it can be destroyed; that
is, 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


• 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 of the first memory location into p. In other words, the
operator new creates an array of 10 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
• 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


• 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


• The statement:
int list[5];
declares list to be an array of 5 components.

CS-203 Object Oriented Programming 32


Because the value of list, 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 of list 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


• If p is a pointer variable of type int, then the statement:

p = list;

copies the value of list (1000, the base address of the array) into p.

• We can perform increment and decrement operations on p.

CS-203 Object Oriented Programming 34


Pointer to Array of Objects
1. #include <iostream> 18. void set(double n, char *s) {
2. #include <new> 19. cur_bal = n;
3. #include <cstring> 20. strcpy(name, s);
4. using namespace std; 21. }

5. class balance { 22. Void set(){


6. double cur_bal; 23. Cout<<“Enter name ”;
7. char name[80]; 24. cin>>name;
8. public: 25. Cout<<“Enter balance”;
9. balance(double n, char *s) { 26. Cin>>cur_bal;
10. cur_bal = n; 27. }
11. strcpy(name, s);
12. } 28. void get_bal(double &n, char *s) {
13. balance() {} // parameterless constructor 29. n = cur_bal;
14. ~balance() { 30. strcpy(s, name);
15. cout << "Destructing "; 31. }
16. cout << name << "\n"; 32. };
17. }

CS-203 Object Oriented Programming 35


Pointer to Array of Objects
1. int main() 13. // note use of dot, not arrow operators
2. { 14. p[0].set(12387.87, "Ralph Wilson");
3. balance *p; 15. p[1].set(144.00, "A. C. Conners");
4. char s[80]; 16. p[2].set(-11.23, "I. M. Overdrawn");
5. double n;
6. int i; 17. for(i=0; i<3; i++) {
18. p[i].get_bal(n, s);
7. try {
8. p = new balance [3]; // allocate entire 19. cout << s << "'s balance is: " << n;
array 20. cout << "\n";
9. } catch (bad_alloc xa) { 21. }
10. cout << "Allocation Failure\n";
11. return 1; 22. delete [] p;
12. } 23. return 0;
24. }

CS-203 Object Oriented Programming 36


Array of Pointers to Objects
1. Int main() 14. For(int i=0; i<n; i++)
2. { 15. {
3. balance p[100]; 16. p[n]->get_bal();
4. Int n=0; char choice; 17. }
5. do 18. Cout<<endl;
6. { 19. Return 0;
7. p[n]=new balance; 20. }
8. P[n]->set();
9. n++;
10. cout<<“Enter another
(Y/N)?”;
11. Cin>>choice;
12. }
13. While(choice==‘Y’); CS-203 Object Oriented Programming 37
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


String Class
• Header file: #include<string>
• Declaration: string Name;
• Reading Embedded blanks:
– getline (cin , Name);
• Reading multiple lines:
– Getline (cin, address, ‘$’) //reads multiple lines till $ is
entered as terminating character.

CS-203 Object Oriented Programming 39


Modifying string objects
#include <iostream>
#include <string>
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 Nothing
is 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 Object Oriented Programming 40

Das könnte Ihnen auch gefallen