Print Matrix Trying to have a 2D array parameter in a function in C isn\'t as si
ID: 3601988 • Letter: P
Question
Print Matrix Trying to have a 2D array parameter in a function in C isn't as simple as in Java. Like with single dimensional arrays, it's common to actually make the parameter a pointer to a pointer type rather than an actual array type. Create a function to print a 2D array of characters. Write a program that asks the user for a height and width and dynamically allocates a 2D array of those dimensions. Fill the array with dots and then randomly put asterisks in some elements. For the number of asterisks, it should be 10% of the width times the height cast to an int (for example, 10 * 10 * 0.1 = 10). Then, use the print function on the array. Here's the function header to get you started:
void print_matrix(char ** matrix, int height, int width)
Sample Run:
Enter Height: 10
Enter Width: 10
Asterisk Count: 10
array (0x7f939d600000):
. . . * . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . * . . . . . .
. . . * . . . * . .
. . . . . . . . . .
. * . . . * . . . .
. . . . . . . * . *
. . * . . . . * . .
. . . . . . . . . .
Explanation / Answer
Here is the program which takes array as a double pointer.
#include<stdio.h>
#include<stdlib.h>
long random_at_most(long max) {
unsigned long
// max <= RAND_MAX < ULONG_MAX, so this is okay.
num_bins = (unsigned long) max + 1,
num_rand = (unsigned long) RAND_MAX + 1,
bin_size = num_rand / num_bins,
defect = num_rand % num_bins;
long x;
do {
x = rand();
}
// This is carefully written not to overflow
while (num_rand - defect <= (unsigned long)x);
// Truncated division is intentional
return x/bin_size;
}
void print_matrix(char **matrix, int r, int c){
int i,j,x,rand1,rand2,count;
// adding dots to the array
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
matrix[i][j] = '.'; // OR *(*(arr+i)+j) = ++count
//calculate the no of stars to be printed
x = (int)(r*c*0.1);
//adding stars to the array
count=0;
while(count<x){
//srand(time(NULL));
rand1 =(int) rand()%10+1;
//srand(time(NULL));
rand1 = (int)rand()%10+1;
//if(rand1 < r && rand2 < c){
matrix[rand1][rand2]='*';
count++;
//}
}
//printing array
for (i = 0; i < r; i++){
for (j = 0; j < c; j++){
printf("%c ", matrix[i][j]);
}
printf(" ");
}
}
int main() {
int height,width,i;
char **matrix;
clrscr();
//taking height from user
printf("Enter Height ");
scanf("%d",&height);
//taking width from user
printf("Enter Width ");
scanf("%d",&width);
//allocating memory for 2d array
matrix = (char **)malloc(height * sizeof(char *));
for (i=0; i<height; i++)
matrix[i] = (char *)malloc(width * sizeof(char));
//calling function to print matrix
print_matrix(matrix, height, width);
getch();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.