ints, doubles, strings,
etc. already.
We create an array of
6 objects of type T like this:
|
For example, we can create an array of 6 ints as follows:
|
We create an array of
6 objects of type T like this:
|
Each object in my array of students is itself an array of
ints, i.e. each element is an int*.
|
So, if the type of object that gets stored in the array is
int*, we create our array like this:
int** A = new int*[6]; |
intas!
A[3] = new int[5];
This will change the picture as shown below:
new int[5] has type
int* (do you see why?).
A[3] has type int* (do you see why?).
A[3][4] can be used to access the last element
of an array that A[3] points to.
int* A[3] = new int[5];
A[3] is merely accessing an element of an array that A points to.
| Naive | Elegant (Use this way) |
|
The following code will create a full 2D array.
|
We can use a loop to make the code simpler:
|
new live on until the end of your program, or until deleted with the
delete [] command.

delete [] A[5];

delete [] A[0];
delete [] A[1];
delete [] A[2];
delete [] A[3];
delete [] A[4];

A points
to!
delete [] A;

for(int i=0; i < 6; i++)
delete [] A[i];
delete [] A;
A?
Answer: int**
A[i]?
Answer: int*
We have a class of 6 students, each with 6 homework grades, and the grade info is stored in a file grades.txt, which looks as follows:
58 96 65 72 93 67 96 67 56 74 94 100 88 81 94 59 95 65 76 97 88 69 64 94 61 91 56 62 81 91 89 52 90 67 56 90In the file each row represents a student. The program answers questions like the following:
how did student 4 do on homework 3?
$ ./a.out (Q)uit or (V)iew? V Student number [0..5]: 3 Homework number [0..5]: 4 Grade was 64 (Q)uit or (V)iew? V Student number [0..5]: 0 Homework number [0..5]: 0 Grade was 58 (Q)uit or (V)iew? QSolution
Note:
For this task, you need to read each individual character including
whitespaces. fin.get() will do the trick. It will return the
ASCII code of a character you read.
$ ./a.out filename: apple.txt > show $$$$ $$$$$$ $$$$$$ $$$$ $$ $$$$$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$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