Write a C program to convert 1D array to 2D array using pointers. Follow the given steps to implement the above code.
- Ask the user to input the number of rows ( m ) and the number of columns ( n ) of the 2D array. So the total number of elements of 1D array = ( m * n ) elements.
Call the function input_array to store elements in 1D array.
void input_array (int *arr,int size) // size = m * nCall the function print_array to print the elements of 1D array.
void print_array (int *arr, int size)Call the function array_to_matrix to convert 1D array to 2D array.
void array_to_matrix(int **matrix, int *arr, int row, int col)Call function print_matrix to print the elements of the 2D array.
void print_matrix(int **mat, int row, int col)
All functions should be called from the main(). Accessing and storing of elements in pointers should be carried out by using pointers only.
Code:
#include <stdio.h>
#include <stdlib.h>
#define max 100
void input_array (int *arr,int size);
void print_array (int *arr, int size);
void array_to_matrix(int **matrix, int *arr, int row, int col);
void print_matrix(int **matrix, int row, int col);
int main()
{
int m, n, arr[max], mat[max][max];
printf("Enter the number of rows(m):");
scanf("%d",&m);
printf("Enter the number of columns(n):");
scanf("%d",&n);
int size = m*n;
input_array (arr,size);
print_array (arr,size);
array_to_matrix(mat, arr, m, n);
print_matrix(mat, m, n);
}
void input_array (int *arr,int size)
{
int i;
for(i=0;i<size;i++)
{
printf("Enter element a[%d]",i);
scanf("%d",&arr[i]);
}
}
void print_array (int *arr, int size)
{
int i;
printf("\n 1D array is as follows : \n");
for(i=0;i<size;i++)
{
printf("%d",arr[i]);
}
}
void array_to_matrix(int **matrix, int *arr, int row, int col)
{
int i,j,k=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
matrix[i][j] = arr[k];
k++;
}
}
}
void print_matrix(int **matrix, int row, int col)
{
int i,j;
printf("\n 2D matrix is as follows : \n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d ",matrix[i][j]);
}
printf("\n");
}
}
Error: I am getting a segmentation fault. The problem I am having is related to pointer to the arrays and how to pass them to the function.
int size = m*n;while n nor m are yet intialized