使用动态内存分配在二维数组中添加值

add values in a 2 dimensional array using dynamic memory allocation

鉴于此任务:

Write a program that allocates the necessary amount of memory for storing the elements from two [m x n] integer matrices.

我不知道如何为二维数组分配内存。
我看了一些例子,但我不明白。

#define _CRT_SECURE_NO_WARNINGS
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#define DIM 10


void main()
{
    int **m, *n;
    int i = 0, j = 0;
    int diml, dimc;;
    puts("Introduceti dimensiunea matricelor(linii|coloane)");
    scanf("%d%d", &diml, &dimc);
    m = (int**)malloc(dimc*sizeof(int));
    puts("Introduceti elementele primei matrici:");
    for (j = 0;j < dimc;j++)
    {
        m[i] = (int *)malloc(diml*(sizeof(int)));
    }
    for (j = 0;j < dimc;j++)
    {
        for (i = 0;i < diml;i++)
        {
            printf("tab[%d][%d]= ", j + 1, i + 1);
            scanf("%*d", m[j][i]);

        }
    }
    _getch();
}

我的程序在输入第一行后崩溃。

Introduceti dimensiunea matricelor(linhi I coloane)
3
3
Introduceti elementele primei matrici:
ab[1][1]= 2
ab[1][2]= 1
ab[1][3]= 2
ab[2][1]=

Problema 3.exe has stopped working
A problem caused the program to stop working correctly.
Windows  will  closethe program and notify you if a solution is
available.

你首先应该这样分配:

m = (int**)malloc(dimc*sizeof(int*));

之后你这样分配:

m[i] = (int *)malloc(sizeof(int));
  1. 通过根据 object 的大小而不是 type[ 的大小进行分配,避免使用错误大小进行分配的错误=48=]。如果 sizeof(int) 小于 sizeof(int *),这将解释 OP 的问题。

    // m = (int**)malloc(dimc*sizeof(int));   // Original
    // m = (int**)malloc(dimc*sizeof(int *)); // corrected type
    // m = malloc(dimc*sizeof(int *));        // cast not needed
    m = malloc(sizeof *m * dimc);             // best : sizeof object
    
  2. 使用正确的索引 ji 。这当然是 OP 的问题。

    for (j = 0;j < dimc;j++) {
      // m[i] = (int *)malloc(diml*(sizeof(int)));
      m[j] = malloc(sizeof *(m[j]) * diml);
    
  3. 确保编译器警告已完全启用 - 它应该捕捉到这个。

    // scanf("%*d", m[j][i]);
    scanf("%d", &m[j][i]);
    
  4. 建议检查malloc()scanf()的结果。

    #include <stdlib.h>
    
    m[j] = malloc(sizeof *(m[j]) * diml);
    if (m[j] == NULL && diml != 0)) {
      fprintf(stderr", "Out of memory\n");
      return EXIT_FAILURE;
    }
    
    if (scanf("%d", &m[j][i]) != 1) {
      fprintf(stderr", "Non-numeric input\n");
      return EXIT_FAILURE;
    }
    
  5. main() 应该 return int.

    #include <stdlib.h>
    int main(void) {
      ...
      return EXIT_SUCCESS;
    }
    
  6. 推广时,确保输出得到打印且未被缓冲。使用 fflush() 或使用 '\n'.

    结束提示
       printf("tab[%d][%d]= ", j + 1, i + 1);
       fflush(stdout);  // add
       scanf(...