add values ​​in a two-dimensional array using a dynamic memory allocation

advertisements

Given this task:

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

I don't know how to allocate memory to 2 Dimensional arrays.
I read some examples but I don't get it.

#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();
}

My program crash after I enter the first line.

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.


  1. Avoid the mistake of allocating using the wrong size by allocating based on the size of the object and not the size of type. If the sizeof(int) was less then sizeof(int *), this would explain OP's problem.

    // 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. Use correct index j vs. i @BLUEPIXY. This is certainly an issue for OP.

    for (j = 0;j < dimc;j++) {
      // m[i] = (int *)malloc(diml*(sizeof(int)));
      m[j] = malloc(sizeof *(m[j]) * diml);
    
    
  3. Insure compiler warnings are fully enabled - it should have caught this one.

    // scanf("%*d", m[j][i]);
    scanf("%d", &m[j][i]);
    
    
  4. Suggest checking the results of malloc() and 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() should return int.

    #include <stdlib.h>
    int main(void) {
      ...
      return EXIT_SUCCESS;
    }
    
    
  6. When promoting, insure output gets printed and is not buffered. Use fflush() or end the prompt with '\n'.

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