variable length multidimensional arrays - c

I did this program for a homework and it crashes without any error when run.
Also after correcting it, any suggestions to increase the efficiency of my coding approach are appreciated.
First I declared m,n,p,q as global variables an I passed only the arrays to the functions, but the program behaved weird.
Then I included the dimensions of the arrays as arguments in every function and declared it everywhere. CRASH
*VLA SUPPORTED
//functions on matrices
#include<stdio.h>
int i, j;
void getMatrix(int m, int n, int values[m][n]);
void displayMatrix(int m, int n, int values[m][n]);
void transposeMatrix(int m, int n, int values[m][n]);
void addMatrices(int m, int n, int p, int q, int A[m][n], int B[p][q]);
void multiplyMatrices(int m, int n, int p, int q, int A[m][n], int B[p][q]);
int main()
{
int m, n, p, q, A[m][n], B[p][q];
printf("Enter the no. of Rows of the first Matrix : ");
scanf("%d", &m);
printf("Enter the no. of Columns of the first Matrix : ");
scanf("%d", &n);
printf("Enter the elements of the first matrix: \n");
getMatrix(m, n, A);
printf("The entered Matrix:\n");
displayMatrix(m, n, A);
printf("The transpose of the entered Matrix:\n");
transposeMatrix(m, n, A);
printf("Enter the no. of Rows of the second Matrix : ");
scanf("%d", &p);
printf("Enter the no. of Columns of the second Matrix : ");
scanf("%d", &q);
printf("Enter the elements of the secong matrix: \n");
getMatrix(p, q, B);
printf("The entered Matrix:\n");
displayMatrix(p, q, B);
printf("The transpose of the entered Matrix:\n");
transposeMatrix(p, q, B);
printf("Addition of the Matrices:\n");
addMatrices(m, n, p, q, A, B);
printf("Multiplication of the Matrices:\n");
multiplyMatrices(m, n, p, q, A, B);
return 0;
}
void getMatrix(int m, int n, int values[m][n])
{
for(i = 0; i < m; ++i)
for(j = 0; j < n; ++j)
scanf("%d", &values[i][j]);
}
void displayMatrix(int m, int n, int values[m][n])
{
for(i = 0; i < m; ++i)
{
for(j = 0; j < n; ++j)
printf("%3d ", values[i][j]);
printf("\n");
}
}
void transposeMatrix(int m, int n, int values[m][n])
{
int transpose[n][m];
for(i = 0; i < n; ++i)
for(j =0; j < m; ++j)
transpose[i][j] = values[j][i];
displayMatrix(n, m, transpose);
}
void addMatrices(int m, int n, int p, int q, int A[m][n], int B[p][q])
{
int C[m][n];
if(m == p && n == q)
{
for(i = 0; i < m; ++i)
for(j = 0; j < n; ++j)
C[i][j] = A[i][j] + B[i][j];
displayMatrix(m, n, C);
}
else
printf("Cannot add these Matrices!\n");
}
void multiplyMatrices(int m, int n, int p, int q, int A[m][n], int B[p][q])
{
int C[m][q], k, sum = 0;
if(n == p)
{
for(i = 0; i < m; ++i)
for(j = 0; j < q; ++j)
{
for(k = 0; k < n; ++k)
sum += A[i][j] * B[j][i];
C[i][j] = sum;
sum = 0;
}
displayMatrix(m, q, C);
}
else
printf("Cannot multiply these Matrices!\n");
}

Initiliazie m and n so that you don't get UB when using them in array index in VLA.
Unsed loop in multiply matrices
for(k = 0; k < n; ++k)
sum += A[i][j] * B[j][i];
will be
for(k = 0; k < n; ++k)
sum += A[i][k] * B[k][j];
Don't use global variables unless you need to. It is good practice to make index variables of for loop local.
for(int i=0;i<n;i++)
...

Related

Creating dynamic two dimensional array in C

I want to write a program that calculates a matrix multiplication.
However, it seems like there is a problem concerning the memory allocation. For m <= 2 and n <= 2, the code works just fine but after staring at it for an hour, I still can't figure out why the program blows up vor values greater than that (SegFault and free_matrix() is complaining about trying to free not allocated memory).
Here is my Code:
#include <stdio.h>
#include <stdlib.h>
typedef double *Vector;
typedef Vector *Matrix;
//Initializes a matrix of given size
Matrix mat_alloc(int m, int n){
Matrix mat = NULL;
mat = (Matrix)malloc(sizeof(m * sizeof(Vector)));
if(mat == NULL){
printf("Error: Not Enough Memory!\n");
return NULL;
}
for(int i = 0; i < m; i++){
mat[i] = (Vector)malloc(n * sizeof(double));
if(mat[i] == NULL){
printf("Error: Not Enough Memory!\n");
return NULL;
}
}
return mat;
}
Matrix mat_mult(Matrix A, Matrix B, int m, int n, int k){
Matrix C = mat_alloc(m, k);
for(int i = 0; i < m; i++){
for(int j = 0; j < k; j++){
C[i][j] = 0;
for(int l = 0; l < n; l++){
C[i][j] += A[i][l] * B[l][j];
}
}
}
return C;
}
void print_matrix(Matrix mat, int m, int n){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
printf("%.2lf ", mat[i][j]);
}
printf("\n");
}
}
void read_matrix(Matrix mat, int m, int n){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
printf("(%d,%d) = ", i+1, j+1);
scanf("%lf", &mat[i][j]);
}
}
}
void free_matrix(Matrix mat, int m){
for(int i = 0; i < m; i++){
free(mat[i]);
}
free(mat);
}
int main(int argc, char *argv[]){
int m = 0;
int n = 0;
int k = 0;
printf("Dimensions of A (m x n):\n");
printf("m = ");
scanf("%d", &m);
printf("n = ");
scanf("%d", &n);
printf("Dimensions of B (n = %d x k):\n", n);
printf("k = ");
scanf("%d", &k);
printf("Your input: m = %d, n = %d, k = %d\n", m, n, k);
Matrix A = NULL;
Matrix B = NULL;
Matrix C = NULL;
A = mat_alloc(m, n);
B = mat_alloc(n, k);
printf("Enter Values for A!\n");
read_matrix(A, m, n);
printf("Enter Values for B!\n");
read_matrix(B, n, k);
printf("A = \n");
print_matrix(A, m, n);
printf("\nB = \n");
print_matrix(B, n, k);
C = mat_mult(A, B, n, m, k);
printf("\nC = \n");
print_matrix(C, m, k);
free_matrix(A, m);
free_matrix(B, n);
free_matrix(C, m);
return 0;
}
Thank you in advance.
This here:
mat = (Matrix)malloc(sizeof(m * sizeof(Vector)));
Should be
mat = (Matrix)malloc(m * sizeof(Vector));
Or better yet
mat = malloc(sizeof *mat * m);
You have a sizeof too much, so instead of getting the desired size of the pointer array, you get a constant (the size of a size_t).

I have to ask user to input an array, a1, of length n. Then use a function to print every third element in an array

I'm very new to C and I can't quite figure out this problem.
I have to use the following function to copy every third element in input array a1[] of length n into output array a2[]
void decimate_by3(int a1[], int n, int a2[])
In the main function:
Ask user to input length of array, and elements in the array.
Calculate length of output array and declare output array.
Call decimate_by3 function
Display output array
I also have constraints which are:
I have to use the defined `void decimate_by3(int a1[], int n, int a2[]) function as is (no modifications)
I am not allowed to declare any other functions
I'm not sure where i'm going wrong but i've attached my work so far.. any help is appreciated :)
#include <stdio.h>
void decimate_by3 (int a1[], int n, int a2[])
int main (void)
{
int n, i;
printf("Enter the length of the array: ");
scanf("%d", &n);
int a1[n];
printf("Enter %d numbers: ", n);
{for (i = 0; i < n; i++)
scanf("%d", &a1[i]);}
int a2[];
if (n % 3 == 0)
int a2[n/3];
decimate_by3 (a1, n, a2);
printf("Output: ");
for (i = 0; i <= (n/3); i++)
{printf(" %d", a2[i]);}
else
int a2[(n/3)+1];
decimate_by3 (a1, n, a2);
printf("Output: ");
for (i = 0; i < n; i++)
{printf(" %d", a2[i]);}
printf("\n");
return 0;
}
void decimate_by3 (int a1[], int n, int a2[])
{
int i;
for (i = 0; i < n; i++)
{
if (i % 3 == 0)
a1[i] = a2[i];
else
delete;
}
}
You will get an error in this line because of a missing semi-colon:
void decimate_by3 (int a1[], int n, int a2[])
You also cannot declare an empty array in C. So this will raise an error:
int a2[];
This code should achieve what you want to do:
#include <stdio.h>
void decimate_by3 (int a1[], int n, int a2[]);
int main (void){
int n, i;
printf("Enter the length of the array: ");
scanf("%d", &n);
int a1[n];
printf("Enter %d numbers: \n", n);
for (i = 0; i < n; i++){
printf("Enter a number: ");
scanf("%d", &a1[i]);
}
int a2[n/3];
decimate_by3(a1, n, a2);
for(i = 0; i < n/3; i++){
printf("%d ", a2[i]);
}
printf("\n");
return 0;
}
void decimate_by3(int a1[], int n, int a2[]){
int i, j = 0;
for(i = 0; i < n; i++){
if((i+1)%3 == 0){
a2[j++] = a1[i];
}
}
}
You're almost there, couple tweaks here and there voila..
void decimate_by3(int a1[], int n, int a2[]);
int main(void) {
int n;
printf("Enter the length of the array: ");
scanf("%d", &n);
if(n <= 0)
return 0;
int a1[n];
printf("Enter %d numbers: ", n);
for (int i = 0; i < n; i++)
scanf("%d", &a1[i]);
int a2[n / 3 + 1];
decimate_by3(a1, n, a2);
printf("Output: ");
for (int j = 0; j < n/3+1; j++)
printf("%i ", a2[j]);
return 0;
}
void decimate_by3(int a1[], int n, int a2[]) {
int cnt = 0;
for (int i = 0; i < n; i++)
if (i % 3 == 0)
a2[cnt++] = a1[i];
}

How to access elements of a matrix array via pointers in C?

I can't seem to find any info on how to access elements of an array via pointer in a function, I tried following multiple answers but none of them seem to work for me.
My task is next: Write a program in C with m x n dimension with elements being randomly generated from 0 to 9. Using two new functions calculate the sum of even elements and count the number of elements being equal to zero.
#include <stdio.h>
#include <stdlib.h>
void SumEven(int *a, int n, int m, int *sum){
}
void EqualToZero(int *a, int n, int m, int *number){
}
int main()
{
int** a;
int m, n, l, i, j, r, sum;
printf("Enter number of columns for matrix: ");
scanf("%d", &m);
printf("Enter number of rows for matrix: ");
scanf("%d", &n);
a = (int **) malloc(m*sizeof(int));
for (l = 0 ; l < m ; l++){
a[l] = (int **) malloc(n*sizeof(int));
}
time_t t;
srand((unsigned)time(&t));
printf("\n");
printf("Your matrix is:\n");
printf("\n");
for(i = 0 ; i < m ; i++){
for(j = 0 ; j < n ; j++){
r = rand() % 10;
a[i][j] = r;
printf("%d ", r);
}
printf("\n");
}
printf("\n");
SumEven(&a, n, m);
return(0);
}
As you can see in the provided code I left those functions empty as I don't know how to pass the matrix to them and access their elements so I can be able to print my results.
Also my pseudo code for the logic for the functions themselves are:
if(a[i][j] % 2 == 0)
printf("%d ", a[i][j])
and
if(a[i][j] == 0)
printf("%d ", a[i][j])
Also those parameters of the function are predefined in my task, so I have to follow them.
EDIT: I also don't know if I'm even passing the same matrix to the function with SumEven(&a, n, m);. I tried outputing the address of the matrix and using printf("%d", &a) to display an address both from main() and SumEven() functions.
This code may help. It does the following:
1. For an arbitrary array of integers, sum the elements of the array
- using a pointer to the SUM function
2. For an arbitrary array of integers, count the number of zero elements in
the array - using a pointer to the COUNTZERO function
#include <stdio.h>
#include <stdlib.h>
// sum the elements of the matrix
void sum(int* arr, int rows, int cols, int* result)
{
int sum = 0;
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
sum = sum + arr[i*cols + j];
}
}
*result = sum;
}
// count the number of zero elements in the matrix
void countZero(int* arr, int rows, int cols, int* result)
{
int count = 0;
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
if (arr[i*cols + j] ==0) count = count + 1;
}
}
*result = count;
}
// arbitrary initialisation of 2D array of ints (force last entry of the array to equal zero - for testing purposes)
void init2D(int *arr, int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
arr[i*cols + j] = 1;
}
}
// use this to test the countZero function
arr[(rows-1)*(cols-1)] = 0;
}
int main() {
int *array; // will hold a 2D array of integers
int N = 10; // arbitrary number of rows
int M = 5; // arbitrary num cols
// 2D array of integers expressed as one "contiguous row" of memory
// make sure your indexing is correct when referenceing the array for (i,j)th element
array = (int*)malloc(sizeof(int)*N*M);
if (array != NULL) {
init2D(array, N, M);
}
// the function pointer
void(*general)(int*,int,int,int*);
// will contain the sum result
int sumAll = 0;
int* ptsumAll = &sumAll;
// make the function pointer point to the sum function
general = ∑
// sum the contents of the array
general(array,N,M, ptsumAll);
printf("sum of array elements: %d\n", *ptsumAll);
// contains a count of the zero elements in the array
int count =0;
int* ptcount = &count;
// make the function pointer point to the count function
general = &countZero;
// count the number of zero element in the array
general(array, N, M,ptcount);
printf("number of zeros: %d\n", *ptcount);
free(array);
return 0;
}
some references:
https://www.cs.swarthmore.edu/~newhall/unixhelp/C_arrays.html
http://www.cprogramming.com/tutorial/function-pointers.html
I have added comments to help you with the code.
#include <stdio.h>
#include <stdlib.h>
void SumEven(int *a, int n, int m, int *sum){
//put this statement in 2 nested for loops of size n and m
if(a[i][j] % 2 == 0)
sum += a[i][j];
}
void EqualToZero(int *a, int n, int m, int *number){
//put this statement in 2 nested for loops of size n and m
if(a[i][j] == 0)
number++;
}
int main()
{
int** a;
int m, n, l, i, j, r, sum;
printf("Enter number of columns for matrix: ");
scanf("%d", &m);
printf("Enter number of rows for matrix: ");
scanf("%d", &n);
a = (int **) malloc(m*sizeof(int));
//should be m*sizeof(int*)
for (l = 0 ; l < m ; l++){
a[l] = (int **) malloc(n*sizeof(int));
//should be cast as (int*)
}
//I suggest you take look at declaring 2d arrays in C
time_t t;
srand((unsigned)time(&t));
printf("\n");
printf("Your matrix is:\n");
printf("\n");
for(i = 0 ; i < m ; i++){
for(j = 0 ; j < n ; j++){
r = rand() % 10;
a[i][j] = r;
printf("%d ", r);
}
printf("\n");
}
printf("\n");
SumEven(&a, n, m);
//need to pass &sum to this function. Also make sure it is initialized to 0
//call EqualToZero() function with proper parameters.
return(0);
//return 0; not return(0);
}
These will be your function prototypes:
void SumEven(int **a, int n, int m,int *sum);
void EqualToZero(int **a, int n, int m,int *number);
since you are passing a(double pointer) from calling then the there should be a double pointer(int **a) to receive it.
Calling:
SumEven(a, n, m,&sum);
EqualToZero(a, n, m,&number);
And this is how you can access the array inside your function:
void SumEven(int **a, int n, int m,int *sum){
int i,j,tsum=0;
for(i = 0 ; i < m ; i++){
for(j = 0 ; j < n ; j++){
if(a[i][j] % 2 == 0)
{
tsum+=a[i][j];
printf("%d ",a[i][j]);
}
}
}
*sum=tsum;
}
Also there is an error in this line a[l] = (int **) malloc(n*sizeof(int)); (‘int**’ to ‘int*’assignment),it should be a[l] = (int *) malloc(n*sizeof(int));.
Here's an example, given a 3D array
int buffer[5][7][6];
An element at location [2][1][2] can be accessed as buffer[2][1][2] or *( *( *(buffer + 2) + 1) + 2).
Reference
if(( *(*(a + i) + j) % 2 ) == 0 )
printf("%d", *(*(a + i) + j) )
if( *(*(a + i) + j) == 0 )
printf("%d", *(*(a + i) + j) )
This is how you do it.

c - warning: pointer argument of a function may be used uninitialized

#include <stdio.h>
#include <stdlib.h>
void multiplyMatrix (int **first, int **second, int **multiply);
int m, n, p, q, i, c, d, k, sum = 0;
int main()
{
int **first, **second, **multiply;
printf("Enter the number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
first = (int **) malloc(m * sizeof(int *));
for(i = 0 ; i < n ; i++){
first[i]=(int *)malloc(m * sizeof(int *));
}
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
second = (int **) malloc(p * sizeof(int *));
for(i = 0 ; i < q ; i++){
second[i]=(int *) malloc(p * sizeof(int *));
}
if (n != p)
printf("Matrices with entered orders can't be multiplied with each other.\n");
else
{
printf("Enter the elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
/*for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}*/
multiplyMatrix(first, second, multiply);
printf("Product of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0;
}
void multiplyMatrix (int **first, int **second, int **multiply)
{
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
}
The program i want to write should be like this: The program asks to the user to enter both the sizes and elements of 2 matrices (or you can call it 2d arrays). Then it will multiply those matrices and print the answer.
The problem i am getting: i used pointers and malloc functions to dynamically allocate the matrices. for the multiplication, i created a function called "multiplyMatrix" which i get a warning for one of the arguments of it in the decleration. here is the warning:
warning: 'multiply' may be used uninitialized in this function.
so there is some kind of a problem with initializing this argument. i feel like the answer is simple but at the same time i can't find the solution.
You have not allocated the memory to be used by the multiply matrix - hence it is being flagged as uninitialised.
You also need to review how you use your row and column values when allocating the first and second matrices, for example:
first = (int **) malloc(m * sizeof(int *));
for(i = 0 ; i < m ; i++){
first[i]=(int *)malloc(n * sizeof(int *));
}
(Incorporates comment made by wildplasser)
This will allow first to be accessed as first[row][col]
the variable multiply was declared in main(), however it is never set to point to anything. it needs to be created the same way as first and second, however it does not need to have its' values filled in.
Suggestions to improve your code:
Create a function to allocate memory for a matrix.
Create a function to read matrix data.
Create a function to deallocate memory of a matrix.
Avoid use of global variables. Pass the necessary arguments to a function.
Use those functions instead of duplicating code in main.
#include <stdio.h>
#include <stdlib.h>
int** createMatrix(int rows, int cols)
{
int i;
int** mat = malloc(sizeof(*mat)*rows);
for ( i = 0; i < rows; ++i )
mat[i] = malloc(sizeof(*mat[i])*cols);
return mat;
}
void readMatrix(int** mat, int rows, int cols)
{
int r;
int c;
for ( r = 0; r < rows; ++r )
for ( c = 0; c < cols; ++c )
scanf("%d", &mat[c][c]);
}
void deleteMatrix(int** mat, int rows)
{
int i;
for ( i = 0; i < rows; ++i )
free(mat[i]);
free(mat);
}
void multiplyMatrix (int **first, int **second, int **multiply,
int frows, int fcols, int scols)
{
int sum = 0;
int r;
int c;
int k;
for (r = 0; r < frows; r++) {
for (c = 0; c < scols; c++) {
sum = 0;
for (k = 0; k < fcols; k++) {
sum += first[r][k]*second[k][c];
}
multiply[r][c] = sum;
}
}
}
int main()
{
int m, n, p, q;
int r, c;
int **first, **second, **multiply;
printf("Enter the number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
first = createMatrix(m, n);
printf("Enter the elements of first matrix\n");
readMatrix(first, m, n);
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
printf("Matrices with entered orders can't be multiplied with each other.\n");
else
{
second = createMatrix(p, q);
printf("Enter the elements of second matrix\n");
readMatrix(second, p, q);
multiply = createMatrix(m, q);
multiplyMatrix(first, second, multiply, m, n, q);
printf("Product of entered matrices:-\n");
for (r = 0; r < m; r++) {
for (c = 0; c < q; c++)
printf("%d\t", multiply[r][c]);
printf("\n");
}
deleteMatrix(multiply, m);
deleteMatrix(second, p);
}
deleteMatrix(first, m);
return 0;
}

How to pass a 2D array as a parameter in C?

The section of function is never entered in the following code
please help me out!
#include<stdio.h>
int findMax(int *a[], int m, int n)//this function is not entering
{
int i,j,k=0;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(k<a[i][j])
k=a[i][j];
printf("hi");//this hi is also not printing
//this hi is just for testing
return k;
}
//This function correct it if possible
int main()
{
int m,n,a[50][50],i,j,k=0;
printf("Enter the number of rows in the matrix\n");
scanf("%d",&m);
printf("Enter the number of columns in the matrix\n");
scanf("%d",&n);
printf("Enter the elements in the matrix\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
printf("The matrix is");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
}
k=findMax((int **)a,m,n);//statements after this is never running but no
//compilation errors
printf("\nThe maximum element in the matrix is %d",k);
return 0;
}
please help me out!!
Thanks to you in advance!!
what you are doing here: int findMax(int *a[], int m, int n) is trying to point at int 50 times, but you want to point at a variabile type int 50 times. therefor you want to decleare the pointer before you decleare the array.
use therefor:
int findMax(int (*a)[], int m, int n)
this should work now without the casting
just turn it into:
k=findmax(a,m,n);
here is a simple tutorial on the subject.
int findMax(int *a[], int m, int n)
int *a[] is an array of pointers to int, you want a pointer to an array of 50 int's:
int findMax(int (*a)[50], int m, int n)
or
int findMax(int a[][50], int m, int n)
You don't need the cast, call it using:
k = findMax(a, m, n);
Or you can use a flat array, an example:
#include <stdio.h>
void foo(int *arr, int rows, int cols)
{
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
printf("%d ", arr[i * cols + j]);
printf("\n");
}
}
#define ROWS 3
#define COLS 3
int main(void)
{
int arr[ROWS * COLS];
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++)
arr[i * COLS + j] = i * COLS + j;
}
foo(arr, ROWS, COLS);
return 0;
}
If you dont know the sizes of the 2d array beforehand you can use malloc:
#include <stdio.h>
#include <stdlib.h>
void foo(int *arr, int rows, int cols)
{
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
printf("%d ", arr[i * cols + j]);
printf("\n");
}
}
int main(void)
{
int i, j, rows, cols;
int *arr;
printf("Num of rows:");
scanf("%d", &rows);
printf("Num of cols:");
scanf("%d", &cols);
arr = malloc(rows * cols);
if (arr == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
arr[i * cols + j] = i * cols + j;
}
foo(arr, rows, cols);
free(arr);
return 0;
}
#include <stdio.h>
#include <limits.h>
#define MATRIX_SIZE 50
int findMax(int a[MATRIX_SIZE][MATRIX_SIZE], int m, int n){
//Valid any of the following is
//int a[MATRIX_SIZE][MATRIX_SIZE]
//int a[][MATRIX_SIZE]
//int (*a)[MATRIX_SIZE]
int i, j, k=INT_MIN;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(k<a[i][j])
k=a[i][j];
return k;
}
int main(void){
int m, n, a[MATRIX_SIZE][MATRIX_SIZE], i, j, k=0;
printf("Enter the number of rows(<=50) in the matrix\n");
scanf("%d",&m);
printf("Enter the number of columns(<=50) in the matrix\n");
scanf("%d",&n);
if(m < 1 || n < 1 || m > 50 || n > 50){
printf("invalid input!\n");
return -1;
}
printf("Enter the elements in the matrix\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("The matrix is");
for(i=0;i<m;i++){
printf("\n");
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
}
k=findMax(a, m, n);
printf("\nThe maximum element in the matrix is %d\n", k);
return 0;
}

Resources