用C写矩阵元素

用C写矩阵元素,c,matrix,C,Matrix,一个矩阵占用了我所有的输入,而B矩阵占用了2或3个元素并崩溃了。当我第一次使用B元素时,它在第一个循环中崩溃了 int main (void) { unsigned int row1, row2, column1, column2; int A[ row1 ][ column1 ]; int B[ row2 ][ column2 ]; printf ("Enter rows and columns of A matrix: "); scanf ("%u%

一个矩阵占用了我所有的输入,而B矩阵占用了2或3个元素并崩溃了。当我第一次使用B元素时,它在第一个循环中崩溃了

int main (void)
{
    unsigned int row1, row2, column1, column2;
    int A[ row1 ][ column1 ];
    int B[ row2 ][ column2 ];

    printf ("Enter rows and columns of A matrix: ");
    scanf ("%u%u", &row1, &column1);

    printf ("Enter rows and columns of B matrix: ");
    scanf ("%u%u", &row2, &column2);

    printf ("Enter elements of A matrix\n");

    for ( i = 0; i < row1; i++ )
    {
        for ( j = 0; j < column1; j++ )
        {
            scanf ("%d", &A[ i ][ j ]);
        }
    } 

    printf ("\n\nEnter elements of B matrix\n");

    for ( i = 0; i < row2; i++ )
    {
        for ( j = 0; j < column2; j++ )
        {
            scanf ("%d", &B[ i ][ j ]);
        }
    }
}
int main(无效)
{
无符号整数第1行、第2行、第1列、第2列;
INTA[第1行][第1列];
int B[第2行][第2列];
printf(“输入矩阵的行和列:”);
scanf(“%u%u”,&row1,&column1);
printf(“输入B矩阵的行和列:”);
scanf(“%u%u”,第2行和第2列);
printf(“输入矩阵的元素\n”);
对于(i=0;i
第1行
第2行
第1列
第2列
未初始化。 这意味着
A
B
的大小不可预测
A
B
只需指向一些内存即可。 然后将数据读入内存,并期望一切顺利。然而,这是一个等待发生的失败。
一旦知道需要多少内存,就应该分配内存。

必须将数组
A
B
的声明移动到第一个
for
循环之前,第二个
scanf()之后

这允许使用有效值初始化变量
row1
row2
column1
column2

使用未初始化的变量会导致未定义的行为

请尝试下面的代码(它适用于带有gcc的linux):


程序具有未定义的行为,因为数组的大小为unsigned int row1、row2、column1、column2;在声明可变长度数组之前未初始化。。。。在第二次
scanf
之后立即声明
int A
int B
。必须始终检查scanf的返回值。总是。毫无例外。
#include <stdio.h>
#include <stdlib.h>

void print_matrix(int *M, int r, int c) {
  int i, j;
  for (i = 0; i < r; i++) {
    for (j = 0; j < c; j++) {
      printf("%d ", *(M + i*c + j));
    }
    printf("\n");
  }
}

int main (void) {
  int i, j, temp;
  unsigned int row1, row2, column1, column2;

  printf ("Enter rows and columns of A matrix: ");
  scanf ("%u%u", &row1, &column1);
  int *A = (int *)malloc(row1 * column1 * sizeof(int));

  printf ("Enter rows and columns of B matrix: ");
  scanf ("%u%u", &row2, &column2);
  int *B = (int *)malloc(row2 * column2 * sizeof(int));

  printf ("Enter elements of A matrix\n");
  for ( i = 0; i < row1; i++ ) {
    for ( j = 0; j < column1; j++ ) {
      scanf ("%d", &temp);
      *(A + i*column1 + j) = temp;
    }
  }

  printf ("\n\nEnter elements of B matrix\n");
  for ( i = 0; i < row2; i++ ) {
    for ( j = 0; j < column2; j++ ) {
      scanf ("%d", &temp);
      *(B + i*column2 + j) = temp;
    }
  }

  printf("\n\nMatrix A:\n");
  print_matrix( A, row1, column1);

  printf("\n\nMatrix B:\n");
  print_matrix( B, row2, column2);

}
$ ./m2
Enter rows and columns of A matrix: 2 3
Enter rows and columns of B matrix: 4 3
Enter elements of A matrix
1
2
3
4
5
6


Enter elements of B matrix
1
2
3
4
5
6
7
8
9
0
1
2


Matrix A:
1 2 3 
4 5 6 


Matrix B:
1 2 3 
4 5 6 
7 8 9 
0 1 2