Michael
Michael

Reputation: 33

Converting matrix to an array in C

How can I copy the elements from a matrix, entered by user, to an array? I tried this, but it didn't work:

 #include<stdio.h>
  int main(){
  int m[20][20],a[400],c=0;//max dimensions;
  scanf("%d %d",&M,&N);//dimensions of matrix;
  for(i=0;i<M;i++{
      for(j=0;j<N;j++{
      scanf("%d", &m[i][j]);
          for(c=0;c<M*N;c++) 
          a[c]=m[i][j];
       }}}

Upvotes: 0

Views: 1418

Answers (1)

Alexander James Pane
Alexander James Pane

Reputation: 648

Don't know why you want to store both the matrix format and the array format, but anyway here is a code that should do the trick with also the data output to show the result:

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

#define R 20 //max rows
#define C 20 //max columns

int main() {
    int m[R][C]; //matrix
    int a[R*C];  //array
    int r, c;    //user matrix size
    int i, j;    //iterators

    printf("insert row size: ");
    scanf("%d", &r);
    printf("insert column size: ");
    scanf("%d", &c);
    if(r > R || c > C) {
        printf("Invalid sizes");
        return -1;
    }

    for(i = 0; i < r; i++) {
        for(j = 0; j < c; j++) {
            printf("insert value for row %d column %d: ", i + 1, j + 1);
            scanf("%d", &m[i][j]);
            a[(c * i) + j] = m[i][j];
        }
    }
    for(i = 0; i < r; i++) {
        for(j = 0; j < c; j++) {
            printf("%d ", m[i][j]);
        }
        printf("\n");
    }
    for(i = 0; i < r * c; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");

    return 0;
}

Note that I also added some checks for the user data, avoiding to generate a matrix bigger that the maximum size. Also you don't need separate loops but it can be done all together.

Upvotes: 1

Related Questions