2

Write a C program to convert 1D array to 2D array using pointers. Follow the given steps to implement the above code.

  1. 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.
  2. Call the function​ ​ input_array​ to store elements in 1D array.

    void input_array (int *arr,int size) // size = ​ m * n

  3. Call the function ​ print_array​ to print the elements of 1D array.

    void print_array (int *arr, int size)

  4. 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)

  5. 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.

3
  • what an idea to do int size = m*n; while n nor m are yet intialized Commented Apr 24, 2020 at 14:49
  • so should int size = m*n; come after m and n are taken? Commented Apr 24, 2020 at 14:52
  • you cannot do the multiplication before to have n and m values yes, but this is not the only error in your code, I will edit my answer Commented Apr 24, 2020 at 14:54

1 Answer 1

2

in

void main()
{
    int m, n, arr[max], mat[max][max];
    int size = m*n;

you compute size while m and n are not yet (possibly) initialized, so the value of size is undefined with undefined behavior

In

 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];
         }
     }
 }

the signature of the function says matrix is an array of pointers to int, but this is not compatible with your main where you use a 2D array. To be compatible :

void array_to_matrix(int (*matrix)[max], int *arr, int row, int col)

and same for print_matrix :

void print_matrix(int (*matrix)[max], int row, int col)

or if you prefer :

void array_to_matrix(int matrix[][max], int *arr, int row, int col)
void print_matrix(int matrix[][max], int row, int col)

But :

Write a C program to convert 1D array to 2D array using pointers

"2D array using pointers" is an is an abuse of language and means a 1D array of pointer to int, there is no 2D array.

In your previous version you limited the dimensions to 100, you do not have a reason to do that, just allocate the arrays in the heap.

Note also k always values 0 in array_to_matrix, so you always use arr[0]

And :

void main()

is wrong, main returns an int

I also encourage you to always check the result of scanf to be sure a valid input was used, else you works with non initialized value with an undefined behavior. When you read the number of rows and columns check there are not less than 1

In print_array to separate the print value with a space will help to make the result readable

Finaly :

#include <stdio.h>
#include <stdlib.h>

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, ** mat;
    int size, i;

    printf("Enter the number of rows(m):");
    if ((scanf("%d",&m) != 1) || (m < 1)) {
      puts("invalid value for rows");
      return -1;
    }

    printf("Enter the number of columns(n):");
    if ((scanf("%d",&n) != 1) || (n < 1)) {
      puts("invalid value for columns");
      return -1;
    }

    size = m*n;
    if (((arr = malloc(size * sizeof(int))) == NULL) ||
        ((mat = malloc(m * sizeof(int))) == NULL)) {
      puts("not enouh memory");
      exit(-1);
    }

    for (i = 0; i < m; ++i) {
      if ((mat[i] = malloc(n * sizeof(int))) == NULL) {
        puts("not enouh memory");
        exit(-1);
      }
    }
    input_array (arr,size);
    print_array (arr,size);
    array_to_matrix(mat, arr, m, n);
    print_matrix(mat, m, n);

    /* free resources */
    free(arr);
    for (i = 0; i < m; ++i)
      free(mat[i]);
    free(mat);

    return 0;
}

void input_array (int *arr,int size)
{
    int i;
    for(i=0;i<size;i++)
    {
        printf("Enter element a[%d]",i);
        if (scanf("%d",&arr[i]) != 1) {
          int c;

          puts("invalid value, redo");

          /* flush invalid value up to the end of line */
          while ((c = getchar()) != '\n') {
            if (c == EOF) {
              puts("EOF, abort");
              exit(-1);
            }
          }

          i -= 1;
        }
    }
}

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++];
        }
    }

}

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");
    }
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -g -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
Enter the number of rows(m):2
Enter the number of columns(n):aze
invalid value for columns
pi@raspberrypi:/tmp $ ./a.out
Enter the number of rows(m):-1
invalid value for rows
pi@raspberrypi:/tmp $ ./a.out
Enter the number of rows(m):2
Enter the number of columns(n):3
Enter element a[0]1
Enter element a[1]aa
invalid value, redo
Enter element a[1]2
Enter element a[2]3
Enter element a[3]4
Enter element a[4]5
Enter element a[5]6

 1D array is as follows : 
1 2 3 4 5 6 
 2D matrix is as follows : 
1 2 3 
4 5 6 
pi@raspberrypi:/tmp $ 
Sign up to request clarification or add additional context in comments.

2 Comments

i have changed it to k++. But how to deal with **matrix??
@Alpha I edited my answer signaling problems and giving a solution, note the statement of you r problem is wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.