CIS 22B - Notes for Tuesday, 10/13

  Announcements and Reminders

Recording

Comments on Assignment 3

  • There is a trend - earlier submitted assignments get better grades
  • Use sample output
  • zero fill
  • assignment of plus or minus suffix
  • store all data in the array
  • missing function with one array element argument
  • ineffective file open check
  • rounding of percents
  • use of stringstream
  • code efficiency & subjective criticism

Pointers Continued

  Pointer Arithmetic
  • With one-dimensional arrays
Example
  • With two-dimensional arrays
Example

  A pointer to pointer

  Other stuff 

Return by address 

pointer to const, const pointer

Dynamic Memory Allocation

  Three types of memory in the computer

  • Stack - for automatic variables, function arguments, and function return values
  • Static - for global contants, and static variables
  • Heap (aka free store) - for dynamic memory allocation

  The new and delete operators

  • new allocates memory
  • delete releases memory
Examples:

int *ptr;
ptr = new int;
*ptr = 6;

or

int* ptr = new int(6);

Where is ptr stored?  Where is the dynamic memory?

Release the memory

delete ptr;

More examples:

float* ptrPI = new float(3.14);
...
delete ptrPI;

char* pc = new char;
*pc = 'x';
...
delete pc;

dog* pSirius = new dog;
...
delete pSirius;

Allocate memory for an array

int * pA = new int[5];
for (int i = 0; i < 5; i++)
     pA[i] = 5 * i;
...
delete [] pA;

char* pName = new char[6];
strcpy(pName,"Harry");
...
cout << *pName;
...
delete [] pName;

Notes:

  • When you allocate memory dynamically, you should release when you are done with it.  Otherwise, you may introduce a memory leak.

  • When you allocate memory for an array, you cannot use initializers to initialize values for the array.
  • When you allocate memory for an array, use square brackets, [ ], to release the memory.
What does it mean, "to move a pointer"?

  Another Example


Simple Example of DMA for char arrays


  Joe's notes on dynamic memory allocation

  Lab Exercise #4

  Put your name, the compiler used, and Lab Exercise #4 in a comment at the top of your program. Email your source code. This lab exercise is due at the beginning of the next lecture

  Write a program that performs the following steps.

  1. Read this file one time to determine how many records it contains.  Be sure to check for a successful file open here.
  2. Close the file.
  3. Allocate memory dynamically to store the data from step 1.  This dynamically allocated memory should be for an array of strings.  The array size should be exactly the number of records from step 1.
  4. Reopen the file and read it a second time, storing each record into the array of strings from step 3.
  5. Print the first and last element in the array.
  6. Release the allocated memory.
  7. Your program output should look like this:
four score and seven years ago our fathers brought forth on this continent a new
earth