[Solved] How to dynamically allocate memory in 2D array and store values? [closed]


As i said problem is in scanning N and M variables.

Change

scanf("%d %d",&N,&N);

to

scanf("%d",&N);
scanf("%d",&M);

and you are fine.

Problem was you were reading N twice while didnt read an M which was used uninitialized.

Non-static variables (local variables) are indeterminate. Reading them prior to assigning a value results in undefined behavior.


You should free all your allocated memory

for(i=0;i<N;i++)
{
    free(A[i]);
}
free(A);

and dont cast malloc()‘s return value becouse

  • Its reduntand
  • Adding the cast may mask failure to include the header stdlib.h, in which the prototype for malloc is found
  • If the type of the pointer is changed, one must fix all code lines where malloc() was called and cast

Next time if you cannot find a bug, try to use debugger and look what exactly is happening, you can see variable values, where would you clearly see that M is uninitialized and didnt change after scanf().

solved How to dynamically allocate memory in 2D array and store values? [closed]