227,757 views
24 votes
24 votes
Create a program which takes two integers as input from the command line. In your code, allocate space for a 2D array dependent on user input. For example, if they enter 30 40 then your program should allocate space using double **. Once the memory is allocated, initialize the data by setting the value at index (i, j) equal to its position a

User Csakbalint
by
2.5k points

1 Answer

12 votes
12 votes

Answer:

In C:

#include <stdio.h>

#include <stdlib.h>

int main() {

int r,c;

printf("Row: "); scanf("%d", &r);

printf("Cols: "); scanf("%d", &c);

double *myarr = (int *)malloc(r * c * sizeof(int));

double inputs = 0.0;

for (int rww = 0; rww < r; rww++){

for (int ccl = 0; ccl < c; ccl++){

inputs= inputs+1.0;

*(myarr + rww*ccl + ccl) = inputs; }}

return 0;}

Step-by-step explanation:

This declares the rows and columns as integers

int r,c;

This gets the number of rows

printf("Row: "); scanf("%d", &r);

This gets the number of columns

printf("Cols: "); scanf("%d", &c);

This dynamically allocate space for array myart

double *myarr = (int *)malloc(r * c * sizeof(int));

This initializes the inputs to the array to 0.0

double inputs = 0.0;

This iterates through the array and initializes each element of the array by its index

for (int rww = 0; rww < r; rww++){

for (int ccl = 0; ccl < c; ccl++){

inputs= inputs+1.0;

*(myarr + rww*ccl + ccl) = inputs; }}

User Pvomhoff
by
2.8k points