0

i want to create a matrix in C, but size of the matrix must be determine by user.There is my code.

int row1,column1;
printf("Please enter number of rows in first matrix: ");
scanf("%d",&row1);
printf("Please enter number of columns in first matrix: ");
scanf("%d",&column1);
int M1[row1][column1];

i get errors with row1 and column1(in the last line).What is the correct way of taking size of a matrix from an user?

Nicolas Defranoux
  • 2,646
  • 1
  • 10
  • 13

4 Answers4

0

You have to dynamically allocate the array as you don't know the size at compile time.

My hint: use a single array it's much simpler:

int M1[] = new int[row1 * column1];

Then address it as

M1[column + line * row1];

If you absolutely need a 2D matrix, refer to this question: How do I declare a 2d array in C++ using new?

And don't forget to delete[] properly your array.

Community
  • 1
  • 1
Nicolas Defranoux
  • 2,646
  • 1
  • 10
  • 13
0

This is because you cannot initialize an array with array length as a variable. Declare a pointer and use malloc to dynamically allocate the array.

int row1,column1;
printf("Please enter number of rows in first matrix: ");
scanf("%d",&row1);
printf("Please enter number of columns in first matrix: ");
scanf("%d",&column1);

int **arr;

//allocate the memory
arr=malloc(sizeof(int*)*row1);

int i;
for (i=0;i<row1;i++)
  *(arr+i)=malloc(sizeof(int)*column1);


//do what you want to do


//free the memory
for (i=0;i<row1;i++)
  free(*(arr+i));

free(arr);
HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33
0

Related: dynamic allocating array of arrays in C

First allocate an array of pointers:

M1 = (int**)malloc(row1 * sizeof(int*));

And then point each to another array.

for(i = 0; i < row1; i++)
  M1[i] = (int*)malloc(column1 * sizeof(int));
Community
  • 1
  • 1
brokenfoot
  • 11,083
  • 10
  • 59
  • 80
0

In c to create matrix of user defined size you need to use dynamic allocation using malloc or alloca(). you can read this link to get information on creating arrays of user defined size in c

Community
  • 1
  • 1
LearningC
  • 3,182
  • 1
  • 12
  • 19