'How to use malloc to assign large two-dimensional arrays in C

I know a very large two-dimensional arrays in C needs a long identifier for the variable type when assigning memory to the array to avoid stack overflow errors and memory issues. Suppose I intend to assign memory to my matrix A which should hold a very large number of numbers using malloc, how am I supposed to go about it?

int main() {

    int rows = 20000;
    int cols = 20000;

    // How do I define the two-dimensional
    // array using 'long int'?
    long long int** A = new long long int(rows);

    // I got that from this site, but it's
    // wrong. How do I go about it?
}


Solution 1:[1]

Use pointers to array:

int main()
{
    size_t rows=20000;
    size_t cols=20000;

    long long int (*A)[cols] = malloc(rows * sizeof(*A));

    //You can use it as normal array.
    A[6][323] = rand();
}

or (but access has different syntax)

int main()
{
    size_t rows=20000;
    size_t cols=20000;

    long long int (*A)[rows][cols] = malloc(sizeof(*A));

    //You can use it almost as normal array.
    (*A)[6][323] = rand();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 0___________