Print Matrix Trying to have a 2D array parameter in a function in C isn\'t as si
ID: 3808147 • 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
First of all I want to clarify one thing , Please check my comments below carefully.
char ** doesn't represent a 2D array - it would be an array of pointers to pointers. You need to change the definition of print_matrix if you want to pass it a 2D array:
or equivalently:
#include<stdio.h>
#include<stdlib.h>
void print_matrix( char **matrix, int height , int width);
int main()
{
char **matrix;
int height, width ;
printf("Enter Height");
scanf("%d",&height); // User Input for height Value
printf(" Enter Width");
scanf("%d",&width);// User input for width value
print_matrix(matrix,height,width); // call print_matrix function
}
void print_matrix( char **matrix, int height , int width) // Definition of function
{
int i,j,num_ast,rand_row,rand_col;
matrix = (int **) malloc(height * sizeof(char *)); // Dynamically allocate memory to row pointers
for (i = 0; i < height; i++) {
matrix[i] = (char *) malloc(width * sizeof(char)); // Dynamically allocate memory to each row pointer
}
for (i=0 ;i < height ;i++)
{
for (j=0 ;j < width ;j++)
{
matrix[i][j] = '.' ; // Assign dot to every element in the array
}
}
num_ast = 0.1 * width * height ; //calculate the number of asteric required
for (i=0;i<num_ast;i++)
{
rand_row = rand() % height ; // randomly generate row number
rand_col = rand() % width ; // randomly generate column number
matrix[rand_row][rand_col] = '*'; // assign asteric value to that element
}
for (i =0 ;i < height ;i++)
{
for (j=0 ;j < width ;j++)
{
printf("%c ",matrix[i][j]) ; // Print matrix
}
printf(" ");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.