Answer to Question #50606 in C++ for Umer

Question #50606
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;
}

system&#40;"pause"&#41;;
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS