As presented, Exercise 9 is rather inelegant because each of the 10 int arrays is declared
in a different program statement, using a different name. Each of their addresses must
also be obtained using a separate statement. You can simplify things by using new, which
allows you to allocate the arrays in a loop and assign pointers to them at the same time:
for(j=0; j<NUMARRAYS; j++) // allocate NUMARRAYS arrays
*(ap+j) = new int[MAXSIZE]; // each MAXSIZE ints long
Rewrite the program in Exercise 9 to use this approach. You can access the elements of
the individual arrays using the same expression mentioned in Exercise 9, or you can use
pointer notation:
*(*(ap+j)+k). The two notations are equivalent.
1
Expert's answer
2015-02-03T12:13:47-0500
#include <stdlib.h> #include <iostream> #include <stdio.h> #include <cstdlib> using namespace std; const int NUM_ARRAYS = 10; const int MAX_SIZE= 10; int main(){
int **arrays = new int *[NUM_ARRAYS]; *arrays = new int[NUM_ARRAYS]; for (int i = 0; i < NUM_ARRAYS; i++) { *(arrays+i) = new int[MAX_SIZE]; } int col = 0; for(int i = 0; i < NUM_ARRAYS; i++){ for(int j = 0; j < MAX_SIZE; j++) { *(*(arrays + i) + j)= col; col += 10; } } for(int i = 0; i < NUM_ARRAYS; i++){ for(int j = 0; j < MAX_SIZE; j++) { cout<<*(*(arrays + i) + j)<<" "; } cout<<endl; }
Comments
Leave a comment