/* As we are assigning random value during the run time, we just have to dynamically allocate the memory and use the pointer as a 2D array directly and assign random values to this 2D array. Here the memory
allocated is only for the columns, now for the rows we just need a for
loop and assign the value for every row a dynamic memory. We can use
the pointer just the way we use a 2D array.*/
// Assigning random values to a 2D array
#include<iostream>
#include<iomanip>#include<stdlib.h>
using namespace std;
int main()
{
int x = 3, y = 3; //user can also ask these value during runtime
int **ptr = new int *[x];
for(int i = 0; i<y; i++)
{
ptr[i] = new int[y];
}
srand(time(0));
for(int j = 0; j<x; j++)
{
for(int k = 0; k<y; k++)
{
int a = rand()%10;
ptr[j][k] = a;
cout<<ptr[j][k]<<" ";
}
cout<<endl;
} system("pause");rerutn 0;}
ScreenShot:



0 comments:
Post a Comment