0

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];
       }}}
4
  • The array copy needs to be done after all the user input is complete. That is, need to move the last for loop out of the existing loops and into a seperate i/j loop. If that still doesn't work for you then please describe the problem in more detail than "didn't work". Give the exact input, expected result and actual result. Commented Dec 29, 2020 at 3:58
  • 1
    That is an aconventional way of writing C code. The Pico style with multiple } markers on a single line is anathema in C (except, presumably, to your professor(s)). You've indented the code by miles, but don't use spaces within lines; that also makes the code harder to read. The indentation isn't consistent; that too makes it harder to read. You have two 'loops' like for(i=0;i<M;i++{ where you've missed the ) before the {. You declare c early, but don't declare i or j at all. It is better if you post code that can be compiled! (The inner loop does not do what you want either.) Commented Dec 29, 2020 at 6:40
  • regarding; scanf("%d %d",&M,&N); The variables M and N are not declared anywhere in the posted code. Therefore, the posted code will not compile! Commented Dec 30, 2020 at 16:39
  • OT: for ease of readability and understanding: (the compiler will not care) 1) please consistently indent the code. Indent after every opening brace '{'. Unindent before every closing brace '}'. Suggest each indent level be 4 spaces. 2) please follow the4 axiom: only one statement per line and (at most) one variable declaration per statement. Strongly suggest treating } as a separate statement. Commented Dec 30, 2020 at 16:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Don't forget that users can type zero or negative numbers for the array dimensions. Validation is hard! And reporting the problem sensibly is hard too. if (r < 1 || r > R) { fprintf(stderr, "The number of rows %d is out of the range %d..%d\n", r, 1, R); exit(EXIT_FAILURE); } tells people more precisely which value was wrong and the range of acceptable values. You might use enumerated constants enum { MIN_ROW = 1, MAX_ROW = 20 } and use those in the conditions and printing. Report errors on standard error, not standard output.
Sure there is a lot more validation to be done, like: checking that the user inputs a numeric value (letters, icons and similar are invalid) for both matrix size and values; check that the introduced value does not overflow the int representation; etc. I just gave a suggestion to keep validation in mind
rather than having to verify the (user entered) values for r and c, strongly suggest using the Variable length array feature of C. I.E. get the values of r and c from the user, then declare the array using r and c.
Sure it is possible to use dynamic memory allocation, but I think this is more complex and out of the scope of the initial question. But I agree that would be more flexible and memory efficient (you would just allocate the minimum necessary memory for the data)

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.