Search code examples
cmatrixallocation

How to define matrix dynamically in C


I created a program that prints 2 dimension matrix from external txt file. My program works if I define static matrix such as A[10][10]. But I want to allocate memory dynamically.

When I try this code:

int **A = (int **)malloc(N * N * sizeof(int));

There is error as following:

Unhandled exception at 0x00AC159B in dataStructures4.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD.

On this loop:

for(i=0; i<N; i++){
    for(j=0; j<N; j++){
        A[i][j] = -1;
    }
}

I think I can't generate dynamic matrix correctly. How should I modify my code?


Solution

  • You dynamically create 2d arrays as a pointer to chunk of int* pointers which point to a chunk of ints.

    So there are two steps:

    1) A to point to the first of a chunk of int*

    int **A = (int **)malloc(N * sizeof(int*));
    

    2) each of them to point to the first of a chunk of ints

    for(i=0; i<N; i++){
        A[i] = (int *)malloc(N * sizeof(int));
    }