Dynamic Array Allocation

advertisement
Dynamic Array Allocation
char *ptr;
// ptr is a pointer variable that
// can hold the address of a char
ptr = new char[ 5 ];
// dynamically, during run time, allocates
// memory for 5 characters and places into
// the contents of ptr their beginning address
6000
6000
ptr
Dynamic Array Allocation
char *ptr ;
ptr = new char[ 5 ];
strcpy( ptr, “Bye” );
ptr[ 1 ] = ‘u’;
// a pointer can be subscripted
std::cout << ptr[ 2] ;
6000
6000
ptr
‘B’
‘u’
‘y’
‘e’
‘\0’
Dynamic Array Deallocation
char *ptr ;
ptr = new char[ 5 ];
strcpy( ptr, “Bye” );
ptr[ 1 ] = ‘u’;
delete [ ] ptr; // deallocates array pointed to by ptr
// ptr itself is not deallocated, but
// the value of ptr is considered unassigned
?
ptr
10.10 Pointers to Structures and
Class Objects

Can create pointers to objects and
structure variables
student stu1;
student *stuPtr = &stu1;
square sq1[4];
square *squarePtr = &sq1[0];

Need () when using *, .
(*stuptr).studentID = 12204;
Chapter 10 slide 4
Structure Pointer Operator


Simpler notation than (*ptr).member
You can use the form ptr->member:
stuptr->studentID = 12204;
squareptr->setSide(14);
in place of the form (*ptr).member:
(*stuptr).studentID = 12204;
(*squareptr).setSide(14);
Chapter 10 slide 5
Dynamic Memory with Objects

Can allocate dynamic structure
variables and objects using pointers:
stuPtr = new student;

Can pass values to constructor:
squarePtr = new square(17);

delete causes destructor to be
invoked:
delete squarePtr;
Chapter 10 slide 6
Download